通过创建条件语句在R中分箱变量

时间:2016-05-27 04:30:44

标签: r

我目前有Time Departed字段。 Time Departed目前归类为"POSIXct" "POSIXt"。我想将其归类为morningafternooneveningnight。 我设计的功能如下:

mysizetwo <- function(x){
 if(x<0)
   return(0)
 if(0 <= x & x < 5)
   return(1)
 if(5<=x & x<12)
   return(2)
 if(12<=x & x<17)
   return(3)
 if(17<=x & x<24)
   return(4) 
 else
   return(NA)
}

dfFinal$TIME_ACTUAL_DEPART.bin <- sapply(dfFinal$TIME_ACTUAL_DEPART, mysizetwo)

变量我想基于

的条件

enter image description here

1 个答案:

答案 0 :(得分:0)

我们可以尝试NSString

findInterval

数据

library(chron)
c("morning", "afternoon", "evening", "night")[findInterval(chron(times =
       sub("\\S+\\s+", "", df1[,1])), 
           times(c("05:00:00", "12:00:00", "18:00:00", "22:00:00")))]
#[1] "morning"   "evening"   "morning"   "evening"   "afternoon" "night"