如何在Rstudio中仅使用日期时间的时间部分

时间:2019-07-16 18:39:30

标签: r datetime

我想仅在rstudio的datetime变量中向时间变量添加ifelse函数,而不会分离出datetime。

尝试过ifelse仅调用时间的功能。

编辑:我希望将8:01-20:00 =白天的时间和20:01-8:00 =晚上的时间,并将所有重叠的东西混合在一起。

#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)

我目前的方法是要么获得所有夜间功能,要么获得所有混合功能,否则将获得NA

1 个答案:

答案 0 :(得分:1)

这是一个解决方案,它使用dplyr::case_when函数与自定义函数一起使用lubridate。希望这会有所帮助!

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