简体   繁体   中英

Aggregate time series from weeks to month

Assume a timeseries ts with frequency(ts) = 52:

Time Series:
Start = c(2010, 34) 
End = c(2013, 25) 
Frequency = 52 
...

I want to aggregate ts such that frequency(ts) = 12.

If the new frequency divides the old one, one can use

aggregate(ts, nfrequency = k, FUN = sum)

But if old frequency mod new frequency > 0 it does not work:

> ts <- aggregate(ts, nfrequency = 12, FUN = sum)
Error in aggregate.ts(ts, nfrequency = 12, FUN = sum) : 
cannot change frequency from 52 to 12

I can a imagine to loop through the time series and decide for each value if to add it completely or a fraction of it, but I am surely not the first one with that requirement. So is there any predefined function doin that?

Yes there are predefined function doing aggregation by month or more generally by any period of time.You can use xts package is very handy for time series manipulations.

For example , you can use apply.monthly :

library(xts)
ts.month <- apply.monthly(as.xts(ts),FUN=sum)

As mentioend, if you do not mind loading another package, I recommend using the aggregate function in zoo or similar functions in xts . You will probably need these packages anyway, especially if you run into ragged timeseries data. Here are examples of aggregating to a monthly timeseries using zoo followed by xts :

zoo:

monthlyTS <- aggregate(dailyTS, as.yearmon, sum)

xts:

monthlyTS <- apply.monthly(xts(dailyTS), mean)

Pure syntactic sugar! What's really nice about xts is that you can aggregate by week. However, it's trivial to add new aggregation functions to the zoo function too.

Cheers,

Adam

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM