gpt4 book ai didi

r - 在 R 中将日期时间标记为早上、下午和晚上

转载 作者:行者123 更新时间:2023-12-04 16:30:06 25 4
gpt4 key购买 nike

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

初始数据

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

关于r - 在 R 中将日期时间标记为早上、下午和晚上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com