将R时间列转换为特定字符串

时间:2014-02-18 08:39:23

标签: r datetime

我有一个列表示R中数据框中的时间。

当我在列上调用str()函数时,它就像这样

>str(df2$Time)
 Factor w/ 1441 levels "","00:01","00:02","00:03",..: 1086 1096 1111 and so on

问题是我想将此列转换为字符串类型,这样如果时间小于12:00,它应该被修改为字符串“moring”,如果时间在12:00和6:00之间,它是“白昼”等等。

我认为第一步是将此向量转换为数据帧的时间类型,因此我使用了chron函数。

我输入了以下命令,

>df2$Time<-chron(times=df2$Time,format=c('h:m'))
 Error in convert.times(times., fmt) : format h:m may be incorrect
 In addition: Warning message:
In is.na(out$s) : is.na() applied to non-(list or vector) of type 'NULL"

所以我猜我应该在格式中添加第二个参数,所以我尝试了以下内容:

df2$Time<-chron(time=df2$Time,format=c('h:m:s'))

但仍然有同样的错误

我知道这只是第一步,可能是我的方法也是错误的。任何人都可以建议我如何将这些时间数据单元转换为早,晚,晚等。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:4)

lubridate相同的事情(对不起Joran,我喜欢这个包),以及hourhm函数:

Time <- hour(hm("13:24","19:32","3:45","08:25", "21:45", "11:13", "00:00"))
your_breaks <- hour(hm("00:00", "6:00", "12:00", "18:00", "23:59"))
your_labels <- c("Night", "Morning", "Afternoon", "Evening")
cut(x=Time, breaks=your_breaks, labels=your_labels, include.lowest=TRUE)

[1] Afternoon Evening   Night     Morning   Evening   Morning   Night

答案 1 :(得分:4)

使用chron的"times"课程和cut

library(chron)

# data in reproducible form
df2 <- data.frame(Times = c("00:01","12:02","19:03"))

df2$Times <- times(paste0(df2$Times, ":00")) # append a chron "times" class column
breaks <- c(0, 12, 18, 24) / 24 # times are internally fractions of a day
labels <- c("morning", "daylight", "evening")
df2$ind <- cut(df2$Times, breaks, labels, include.lowest = TRUE)

给出:

> df2
     Times      ind
1 00:01:00  morning
2 12:02:00 daylight
3 19:03:00  evening

下次请以可复制的形式提供您的数据。

已修订轻微简化和修正错字。

答案 2 :(得分:1)

首先是一些可重复的例子:

time <- expand.grid(0:23,0:59)
time <- apply(time,1,function(x)sprintf("%02i:%02i",x[1],x[2]))

一种方法是在您的小时数据前粘贴一些假日期,以便您可以将时间数据解析为POSIXct,然后使用cut对它们进行排序:

time <- strptime(paste("01/01/01",time),"%y/%m/%d %H:%M")

cut(time,
    breaks= as.POSIXct(paste("2001-01-01",
                       c("00:00:00", "12:00:00", "18:00:00", "23:59:59"))),
    labels=c('morning','afternoon','night'))