lubridate
您可以使用和实现此目的cut
。
library(lubridate)
# transform into date time column (if it is not already one)
df$Time_stamp <- ymd_hms(df$Time_stamp)
# create breaks
breaks <- hour(hm("00:00", "6:00", "12:00", "18:00", "23:59"))
# labels for the breaks
labels <- c("Night", "Morning", "Afternoon", "Evening")
df$Time_of_day <- cut(x=hour(df$Time_stamp), breaks = breaks, labels = labels, include.lowest=TRUE)
df
Id Time_stamp Time_of_day
1 3083188c 2016-08-29 13:10:51 Afternoon
2 924d500e 2016-08-29 09:22:33 Morning
3 ad4dd7ff 2016-08-25 20:29:35 Evening
数据:
df <- structure(list(Id = c("3083188c", "924d500e", "ad4dd7ff"),
Time_stamp = c("2016-08-29 13:10:51", "2016-08-29 09:22:33", "2016-08-25 20:29:35")),
.Names = c("Id","Time_stamp"),
class = "data.frame",
row.names = c(NA, -3L))