Aggregate a data frame in R by equally spaced time intervals

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 23:17:46

问题


I want to aggregate the data by time and create equally spaced time intervals:

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

What I want:

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

Is there anyway to do this without using zoo or xts?


回答1:


I'm assuming by your last line that you are trying to avoid using packages.

Sticking with base R, you can try tapply, but your dates will become the rownames (or names, if you skip the data.frame step):

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


来源:https://stackoverflow.com/questions/23401412/aggregate-a-data-frame-in-r-by-equally-spaced-time-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!