lundi 24 juin 2019

If statement in R uses only first condition to all of the statements. Why?

The below Function which is using to count time in some ranges uses only one condition to all of the statements. Why?

I have been trying to use "any" function to vectorize this statements but it still doesn't work


data <- data.frame(date1=c(as.POSIXct("2016-01-15 13:04:00"),
as.POSIXct("2016-02-25 15:04:00"),as.POSIXct("2016-02-25 15:04:00"),
as.POSIXct("2016-02-25 15:04:00"),as.POSIXct("2012-10-10 17:50:00"),
as.POSIXct("2016-04-14 13:15:00"),as.POSIXct("2016-07-13 08:32:00"),
as.POSIXct("2016-07-13 08:35:00"),as.POSIXct("2016-07-13 08:36:00"),
as.POSIXct("2016-08-09 11:57:00")),

date2=c(as.POSIXct("2018-12-20 16:49:00"),as.POSIXct("2018-12-20 16:50:00"),
        as.POSIXct("2018-12-20 16:50:00"),as.POSIXct("2018-12-20 16:54:00"),
        as.POSIXct("2019-01-11 16:52:00"),as.POSIXct("2019-01-22 11:09:00"),
        as.POSIXct("2019-01-22 11:46:00"),as.POSIXct("2019-01-22 11:26:00"),
        as.POSIXct("2019-01-22 11:18:00"),as.POSIXct("2019-01-22 11:19:00")),

Mid.Category=c("A12","BN1","BN1","BN1","A06","A06","A06","A06",
"A06","A06"),

true_time=c(14983.77,12223.78,12223.78,
                            12223.85,31975.05,14179.92,
                            12925.25,12924.87, 12924.72,
                            12543.38))




data$Mid.Category <- as.character(data$Mid.Category)
str(data)



#################### FUNCTION ###############################

function_SLA <- Vectorize(function(date1,date2){

library(lubridate)


dni_wolne <- c("2018-01-01","2018-01-06","2018-04-01","2018-04-02",
              "2018-05-01","2018-05-03","2018-05-20","2018-05-30",
              "2018-08-15","2018-11-01","2018-11-11","2018-11-12",
              "2018-12-25","2018-12-26","2019-01-01","2019-01-06",
              "2019-04-21","2019-04-22","2019-05-01","2019-05-03",
              "2019-06-09","2019-06-20","2019-08-15","2019-11-01",
              "2019-11-11","2019-12-25","2019-12-26")


if(data$Mid.Category %in% c("B06","B12","BN0","BN1")){


dates <- seq(from=date1,to=date2,"mins")
dates <- dates[which(weekdays(dates) %in% c("poniedziałek","wtorek",
"środa","czwartek","piątek","sobota")

                  & hour(dates) >= 8 & hour(dates) <22
                  & !(as.character(dates,format="%Y-%m-%d") %in% dni_wolne))]

dates <- length(dates)/60


} else if(data$Mid.Category %in% c("A06","A12","AN0")){

dates <- seq(from=date1, to=date2, "mins")

dates <- dates[which(hour(dates) >= 8 & hour(dates) < 22)]

dates <- length(dates)/60
}
return(dates)
}


)

data$wynik <- function_SLA(data$date1,data$date2)


Time that is counting based on this function has to be the same as true_time in data frame but it is true only for one condition in this function. Second condition is counting based on other statement

Aucun commentaire:

Enregistrer un commentaire