将时间对象转换为R中的分类(早,午,晚,夜)变量?

时间:2018-03-19 18:52:51

标签: r time

我在数据帧中有这个向量,格式为小时:我希望转换为分类时间的分钟数:

    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)

我想我会考虑早上5-11,下午11-16,晚上16-19,以及任何事情,直到5晚。使用strptime()时,原始数据的时间格式为小时:分钟。

我在论坛上发现了一些类似的问题,但我似乎无法调整代码来处理我的数据。

5 个答案:

答案 0 :(得分:3)

time <- as.POSIXct(strptime(c("15:03", "08:01", "11:59", "23:47", "14:20"),"%H:%M"),"UTC")

x=as.POSIXct(strptime(c("050000","105959","110000","155959","160000",
                        "185959"),"%H%M%S"),"UTC")
library(tidyverse)
case_when(
between(time,x[1],x[2]) ~"morning",
between(time,x[3],x[4]) ~"afternoon",
between(time,x[5],x[6]) ~"evening",
TRUE ~"night")
[1] "afternoon" "morning"   "afternoon" "night"     "afternoon"

使用基数R:

time <- as.POSIXct(strptime(c("15:03", "08:01", "11:59", "23:47", "14:20"),"%H:%M"),"UTC")

x=as.POSIXct(strptime(c("000000","050000","110000","160000","190000","235959"),
                      "%H%M%S"),"UTC")
labs=c("night","morning","afternoon","evening","night")
labs[findInterval(time,x)]
[1] "afternoon" "morning"   "afternoon" "night"     "afternoon"

答案 1 :(得分:1)

我认为这样就完成了,我不确定如何切割复制标签,但也许其他人会这样做。关键是使用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

更新

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"

答案 2 :(得分:0)

使用一些regexifelse

df$hour <- as.numeric(gsub("\\:.*$", "", df$time))
df$cat <- with(df,  ifelse(hour >= 5 & hour<=11, "morning",
                            ifelse(hour>11 & hour<=16, "evening", "night")))
df
   time hour     cat
1 15:03   15 evening
2 08:01    8 morning
3 11:59   11 morning
4 23:47   23   night
5 14:20   14 evening

答案 3 :(得分:0)

这个类似于@Onyambu,仅使用plyr的{​​{1}}和mapvalues()的{​​{1}}:

lubridate

答案 4 :(得分:0)

我能够使用ifelse语句来制作类别。我将strptime更改为as.POSIXct,并且只保留了制作小组的时间。在df中有3列代表原始时间,只有小时,然后是组。如果类别需要是一个因素,您可以将其更改为as.factor的因子。

time <- c("15:03", "08:01", "11:59", "23:47", "14:20")

time2 <- format(as.POSIXct(time, tz = "" , format = "%H: %M"), "%H")

df <- data.frame(time, time2 = as.numeric(time2))

df$time_category <- ifelse(df$time2 >= 05 & df$time2 <= 11, "Morning",
            ifelse(df$time2 > 11 & df$time2 <= 16, "Afternoon",
            ifelse(df$time2 > 16 & df$time2 <= 19, "Evening", "Night")))