Convert time object to categorical (morning, afternoon, evening, night) variable in R?

后端 未结 5 970
青春惊慌失措
青春惊慌失措 2020-12-19 20:38

I have this vector in a data frame of times in the format of hours:minutes that I want converted to categorical times of day:

    time <- c(\"15:03\", \"0         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 21:12

    I think this gets it done, I'm not sure how to get cut to acept duplicate labels, but maybe someone else will. The key was to use chron::times() to create a chronological object instead of a datetime object.

    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
    

    update:

    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"
    

提交回复
热议问题