0

I want to add ifelse function to time variable only in datetime variable in rstudio without separating out datetime.

Have tried ifelse function only calling time.

Edit: I want times between 8:01-20:00 = day and times between 20:01-8:00 = night, and anything that overlaps both to be mixed.

#Current database
id<-c("m1","m1","m1","m2","m2","m2","m3","m4","m4")
x<-c("2020-01-03 10:00:00","2020-01-03 16:00:00","2020-01-03 19:20:00","2020-01-05 10:00:00","2020-01-05 15:20:00","2020-01-05 20:50:00","2020-01-06 06:30:00","2020-01-08 06:30:00","2020-01-08 07:50:00")
start<-strptime(x,"%Y-%m-%d %H:%M:%S")
y<-c("2020-01-03 16:00:00","2020-01-03 19:20:00","2020-01-03 20:50:00","2020-01-05 15:20:00","2020-01-05 20:50:00","2020-01-05 22:00:00","2020-01-06 07:40:00","2020-01-08 07:50:00","2020-01-08 08:55:00")
end<-strptime(y,"%Y-%m-%d %H:%M:%S")
mydata<-data.frame(id,start,end)

#output
day.night<-c("day","day","mixed","day","mixed","night","night","night","mixed")
newdata<-cbind(mydata,day.night)

My current method I either get all night function or all mixed-function or else NA.

Sparky
  • 349
  • 1
  • 12

1 Answers1

1

Here is a solution, this uses dplyr::case_when with a custom function using lubridate functions. Hope this helps!

library(dplyr)

# Creating the function to filter with
hour_min <- function(x) lubridate::hour(x) + lubridate::minute(x)/60

mydata %>%
  mutate(day.night = case_when(hour_min(start) > 8 & hour_min(start) <= 20 & hour_min(end) > 8 & hour_min(end) <= 20 ~ "day",
                               (hour_min(start) <= 8 | hour_min(start) > 20) & (hour_min(end) <= 8 | hour_min(end) > 20) ~ "night",
                               TRUE ~ "mixed"))

  id               start                 end day.night
1 m1 2020-01-03 10:00:00 2020-01-03 16:00:00       day
2 m1 2020-01-03 16:00:00 2020-01-03 19:20:00       day
3 m1 2020-01-03 19:20:00 2020-01-03 20:50:00     mixed
4 m2 2020-01-05 10:00:00 2020-01-05 15:20:00       day
5 m2 2020-01-05 15:20:00 2020-01-05 20:50:00     mixed
6 m2 2020-01-05 20:50:00 2020-01-05 22:00:00     night
7 m3 2020-01-06 06:30:00 2020-01-06 07:40:00     night
8 m4 2020-01-08 06:30:00 2020-01-08 07:50:00     night
9 m4 2020-01-08 07:50:00 2020-01-08 08:55:00     mixed
Andrew
  • 5,028
  • 2
  • 11
  • 21