以等间隔的时间间隔在R中聚合数据帧

时间:2014-05-01 03:02:34

标签: r dataframe time-series aggregate

我希望按时间汇总数据并创建等间隔的时间间隔:

date<- c(as.POSIXct("2011-08-08 21:00:00"), as.POSIXct("2011-08-08 21:26:00"))
value<-c(1,2)
dt<-data.frame(date, value)

DT<-aggregate(cbind(dt$value),list(cut(dt$date, breaks="10 min")),sum) 

dt:
2011-08-08 21:00:00 1
2011-08-08 21:26:00 2

DT:
2011-08-08 21:00:00 1
2011-08-08 21:20:00 2

我想要的是什么:

2011-08-08 21:00:00 1
2011-08-08 21:10:00 NA
2011-08-08 21:20:00 2

无论如何不使用zoo或xts吗?

1 个答案:

答案 0 :(得分:1)

我在你的最后一行假设你试图避免使用包。

坚持使用基础R,您可以尝试tapply,但如果您跳过rownames步骤,则您的日期将变为names(或data.frame

data.frame(value = tapply(cbind(dt$value),
                          list(cut(dt$date, breaks="10 min")),
                          sum))
#                     value
# 2011-08-08 21:00:00     1
# 2011-08-08 21:10:00    NA
# 2011-08-08 21:20:00     2
相关问题