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

后端 未结 5 969
青春惊慌失措
青春惊慌失措 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:04

    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"
    

    Using base 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"
    

提交回复
热议问题