0
votes

I have a 20-year monthly XTS time series

Jan 1990 12.3

Feb 1990 45.6

Mar 1990 78.9

..

Jan 1991 34.5

..

Dec 2009 89.0

I would like to get the average (12-month) year, or

Jan xx

Feb yy

...

Dec kk

where xx is the average of every January, yy of every February, and so on.

I have tried apply.yearly and lapply but these return 1 value, which is the 20-year total average

Would you have any suggestions? I appreciate it.

1
You could find useful this answer additionally you can plot them using monthplot() - Jilber Urbina
Thank you. Jilber. That post had what I was looking for. - F. Brazil

1 Answers

0
votes

The lubridate package could be useful for you. I would use the functions year() and month() in conjunction with aggregate():

library(xts)
library(lubridate)

#set up some sample data
dates = seq(as.Date('2000/01/01'), as.Date('2005/01/01'), by="month")
df = data.frame(rand1 = runif(length(dates)), rand2 = runif(length(dates)))
my_xts = xts(df, dates) 

#get the mean by year
aggregate(my_xts$rand1, by=year(index(my_xts)), FUN=mean)

This outputs something like:

2000 0.5947939
2001 0.4968154
2002 0.4941752
2003 0.5291211
2004 0.6631564

To find the mean for each month you can do:

#get the mean by month
aggregate(my_xts$rand1, by=month(index(my_xts)), FUN=mean)

which will output something like

1  0.5560279
2  0.6352220
3  0.3308571
4  0.6709439
5  0.6698147
6  0.7483192
7  0.5147294
8  0.3724472
9  0.3266859
10 0.5331233
11 0.5490693
12 0.4642588