如何离职小时?

时间:2018-03-07 04:14:21

标签: r lubridate

我有一些时间值,我试图根据3个类别离婚:早上(4.30,12.00),晚上(12.00,21.00),晚上(21.00,4.30)

首先,我尝试使用lubridate将字符向量转换为字符

library(lubridate)
h <- hm(c("14:30", "02:10", "06:30", "14:50", "20:30", "21:00", "12:00", "23:30", "08:10", "00:00"))

现在我需要离婚h

我通常会使用cut,但它似乎无法在这里工作:

cut(h, breaks = hm(c('4.30', '12.00', '21.00')), levels = c('morning', 'evening', 'night'))

在lubridate中是否有特定的功能?

3 个答案:

答案 0 :(得分:2)

我们可以将其转换为times对象

library(chron)
t1 <- times(paste0(v1, ":00"))

然后通过将cut指定为breaks

来执行times
cut(t1, breaks = times(c('04:30:00', '12:00:00', 
            '21:00:00', '21:00:01')), labels = c('morning', 'evening', 'night'))
#[1] evening <NA>    morning evening evening evening morning <NA>    morning <NA>   
#Levels: morning evening night

#Levels: morning evening night

或者可以使用strptime

中的base R来完成此操作
res <- cut(strptime(v1, format = "%H:%M"), breaks = strptime(c("04:30", "12:00", 
   "21:00", "21:01"), format = "%H:%M"), 
   labels = c("morning", "evening", "night"))
res[is.na(res)] <- "night"
res
#[1] evening night   morning evening evening night   evening night   morning night  
#Levels: morning evening night

数据

v1 <- c("14:30", "02:10", "06:30", "14:50", "20:30",
            "21:00", "12:00", "23:30", "08:10", "00:00")    

答案 1 :(得分:1)

您可以使用基础R中的findInterval

breaks=strptime(c("0.00","4.00","12.00","21.00","23.59"),"%H.%M")
labels=c("night","morning","evening","night")
labels[findInterval(strptime(dat,"%H:%M"),breaks)]
 [1] "evening" "night"   "morning" "evening" "evening" "night"   "evening"
 [8] "night"   "morning" "night"  

其中

 dat <- c("14:30", "02:10", "06:30", "14:50", "20:30",
        "21:00", "12:00", "23:30", "08:10", "00:00")    

我们可以看到dat 2已被赋予night

答案 2 :(得分:1)

另一种选择是将时间转换为数字,然后您可以在arules中使用离散化函数。这可以灵活使用日期等。

require(arules)
h <- data.frame(V1=(c("14:30", "02:10", "06:30", "14:50", "20:30", "21:00", "12:00", "23:30", "08:10", "00:00")))
h$V2<- gsub("\\:", "", h$V1)
h$discrete=discretize(h$V2,method="fixed",categories=c(0,1430,1200,2100,Inf))