在 R 中将一天的时间标记为早上、下午和晚上

Label day timing into morning, afternoon and evening in R

如何为给定的时间戳标记一天中的时间(早上、下午和晚上)?

初始数据

Id            Time_stamp
3083188c     2016-08-29 13:10:51
924d500e     2016-08-29 09:22:33
ad4dd7ff     2016-08-25 20:29:35

最终数据

 Id            Time_stamp              Time_of_day
3083188c     2016-08-29 13:10:51        Afternoon
924d500e     2016-08-29 09:22:33        Morning
ad4dd7ff     2016-08-25 20:29:35        Evening

您可以使用 lubridatecut 来实现。

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