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

标签 r time data-transform wrangle

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

初始数据

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/

相关文章:

不同乘法大小的 Fortran matmul 函数的次数

python - 快速删除包含其他列表元组的元组

R mlogit 包 : use LAPACK instead of LINPACK

android - 手动更改时间时获取 android.intent.action.TIME_SET 两次

r - 当前值不为 1 时,用前值代替当前值,直到在 R 中找到下一个非 1 值

c# - Unity WaitForSeconds 不工作 c#

java - 使用 Java 将 RTF 转换为 XML

r - 将具有数字和普通数字向量的字符矩阵转换为数字

r - 基于包 rgl 在 3D 中绘制箭头

r - 如何删除 R 中字符串中各个位置以特定字符 (@) 开头的任何内容?