Paul 的回答很棒,但我只想补充一点,chron 包有许多出色的日期/时间分类操作,可以与 plyr 配对进行聚合
library("chron")
# chron uses chron-specific object representation.
# If a different representation is needed, a conversion is necessary
# eg. if a$date is a chron date object, I would us as.POSIXct(a$date) to get a POSIXct representation
# create chron date objects and values
a<-data.frame(date=as.chron(Sys.Date() + 1:1000), value = 1:100*runif(100,0,1))
# cuts dates into 15 intervals
a$interval1<-cut(a$date,15)
# cuts dates into 10 number of intervals using a label you define
a$interval2<-cut(a$date,10,paste("group",1:10))
# cuts dates into weeks
a$weeks<-cut(a$date,"weeks",start.on.monday=FALSE)
# cuts dates into months
a$months<-cut(a$date,"months")
# cuts dates into years
a$years<-cut(a$date,"years")
# classifies day based on day of week
a$day_of_week<-day.of.week(a$date)
# creating a chron time object
b<-data.frame(day_time=as.chron(Sys.time()+1:1000*100), value = 1:100*runif(100,0,1))
# cuts times into days - note: uses first time period as the start
b$day<-cut(b$day_time,"days")
# truncates time to 5 minute interval
b$min_5<-trunc(b$day_time, "00:05:00")
# truncates time to 1 hour intervals
b$hour1<-trunc(b$day_time, "01:00:00")
# truncates datetime to 1 hour and 2 second intervals
b$days_3<-trunc(b$day_time, "01:00:02")
我经常使用 chron,因为它使时间聚合变得更加容易。
此外,zoo 和 xts 包还有更多功能,这些功能非常适合在一天的细节级别之后进行各种聚合。他们的文档非常庞大,可能很难找到您想要的东西,但几乎所有您想要的东西都在那里。一些亮点:
library("zoo")
library("xts")
?rollapply
?rollsum
?rollmean
?rollmedian
?rollmax
?yearmon
?yearqtr
?apply.daily
?apply.weekly
?apply.monthly
?apply.quarterly
?apply.yearly
?to.minutes
?to.minutes3
?to.minutes5
?to.minutes10
?to.minutes15
?to.minutes30
?to.hourly
?to.daily
?to.weekly
?to.monthly
?to.quarterly
?to.yearly
?to.period