我将这个向量放在时间数据框中,格式为小时:分钟,我想将其转换为一天中的分类时间:
time <- c("15:03", "08:01", "11:59", "23:47", "14:20")
df$time <- format(strptime(df$time, tz = "" , format = "%H: %M"), format = "%H: %M")
df <- data.frame(time)
Run Code Online (Sandbox Code Playgroud)
我想我会考虑早上 5 点到 11 点,下午 11 点到 16 点,晚上 16 点到 19 点,以及除此之外的任何时间,直到晚上 5 点。原始数据的时间格式为小时:分钟,使用 strptime()。
我在论坛上发现了一些类似的问题,但我似乎无法调整代码来处理我的数据。
我认为这已经完成了,我不确定如何接受重复的标签,但也许其他人会。关键是使用chron::times()创建时间对象而不是日期时间对象。
time <- c("15:03", "08:01", "11:59", "23:47", "14:20")
timep <- as.POSIXct(time, format = "%H:%M") %>% format("%H:%M:%S")
cut(chron::times(timep) , breaks = (1/24) * c(0,5,11,16,19,24),
labels = c("night", "morning", "afternoon", "evening", "night1"))
# [1] afternoon morning afternoon night1 afternoon
# Levels: night morning afternoon evening night1
Run Code Online (Sandbox Code Playgroud)
tod <- cut(chron::times(timep) , breaks = (1/24) * c(0,5,11,16,19,24))
c("night","morning","afternoon","evening","night")[as.numeric(tod)]
# "afternoon" "morning" "afternoon" "night" "afternoon"
Run Code Online (Sandbox Code Playgroud)