user3910073
user3910073

Reputation: 531

Aggregate time series object by month R

I have a time series object in R like this

anom_tsUNAD <-  ts(data, start=c(1922,1), frequency=12)

and I would like to plot the mean value for each month without converting it to a data frame. Any suggestion?

Thanks

Upvotes: 1

Views: 3858

Answers (2)

Adam Erickson
Adam Erickson

Reputation: 6363

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

Upvotes: 2

akrun
akrun

Reputation: 886938

We could get the mean for each 'month' using tapply and then plot

 meanVal <- tapply(anom_tsUNAD, cycle(anom_tsUNAD), FUN=mean)
 plot(meanVal)

The cycle gives the numeric position in the cycle for each observation. For 'Jan' it is 1 and 'Dec' it is 12. We use that as a grouping variable in the tapply to calculate the mean.

data

 anom_tsUNAD <- ts(1:40, start=c(1922,1), frequency=12)

Upvotes: 4

Related Questions