如何将字符时间数据放入一个因子中

时间:2017-04-10 11:37:02

标签: r dataframe data.table

dataframe(Mydata)包含值。

Delivery.Time   Customer.Name              Product.Name
11:22:00        Grace Wangen               Insalatone pollo
19:46:47        ystein Skagestad           CLASSIC CHEESEBURGER
08:54:20        Hans Hallseth              Latte
15:25:21        Thomas Stlen               SUSHI MORIAWASE     
14:45:00        Ingvild Berg               SUSHI CHIISAI
12:45:33        Christopher Frenning       Funghi

Mydata["Delivery.Labels"] <- NA   ## Added new columns

deliBreaks <- c("19:00:00","05:00:00","11:00:00","12:00:00","15:00:00")


Mydata$Delivery.Labels <-c("Dinner", "Breakfast", "Brunch", "Lunch", "Snackstime")[ findInterval(chron(times=Mydata$Delivery.Time), chron(times=deliBreaks))]

在运行代码时,我收到以下错误消息。

  

&#39; VEC&#39;必须非递减地排序

我正在寻找我的桌子。

Delivery.Time   Customer.Name              Product.Name                      Delivery.Lables 

11:22:00        Grace Wangen               Insalatone pollo           Brunch
19:46:47        ystein Skagestad           CLASSIC CHEESEBURGER           Dinner
08:54:20        Hans Hallseth              Latte                      Breakfast
15:25:21        Thomas Stlen               SUSHI MORIAWASE                Snackstime
14:45:00        Ingvild Berg               SUSHI CHIISAI              Lunch
12:45:33        Christopher Frenning       Funghi                     Lunch

1 个答案:

答案 0 :(得分:0)

以下是一个最小的例子。 首先将数据转换为时间数据。 然后使用cut()函数将数据分成时间块。

time<- strptime(c("11:22:00", "19:46:47", "08:54:20", "15:25:21", "14:45:00", "12:45:33"),  format= "%T") 


Delivery.Labels <-    cut(time, breaks = strptime(c("00:00:01", "11:00:00","12:00:00","15:00:00", "19:00:00", "23:59:59"),  "%T"), 
        labels = c("Breakfast", "Brunch", "Lunch", "Snackstime", "Dinner"), 
       right = TRUE,
        include.lowest=TRUE
        )

strptime()将字符串转换为时间。 cut()将您的数据放入箱中。 您可能希望对结果因子进行排序。