Zelong
Zelong

Reputation: 2556

Plot monthly time series with zoo in R

I have a daily time series read in as zoo and I aggregate the time series by month to compute the mean:

# ts is the original daily time series
# ts is a zoo 
m = aggregate(ts, by=months, mean)

The aggregated date m looks like (the values are fabricated):

April  August  December  February  January  July  
40      80       120     20        10       70  

June  March  May  November  October  September    
60    30     50   110       100      90


# Check the class of index
> class(index(m))
[1] "character"

# Subsetting manually
> m[c('January', 'December']
[1] December  January 
    120       10

Obviously, the index of m is sorted by character internally, which makes the line chart difficult to read.

How to sort the aggregated time series m by month?

Upvotes: 0

Views: 478

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269556

Assuming the input shown:

library(zoo)
ts <- zoo(1:12, as.Date(as.yearmon(2000) + 0:11/12))

aggregate(ts, by = match(months(index(ts)), month.name), mean)

Note that month.name is built into R.

Please make sure your questions are reproducible. The input in the question is missing.

Upvotes: 2

Sharon
Sharon

Reputation: 3756

Another option for G. Grothendleck's idea would be

aggregate(x, by = gsub("\d\d\d\d-(\d\d)-\d\d", "\1", as.character(index(x))), mean)

When I tried G.Grothendleck's original code I got an error, but perhaps I did something wrong when creating the test data

library(quantmod)
getQuote("APPL")
x <- as.zoo(x)
aggregate(x, by = match(months, month.name), mean)

Produced:

# Error in match(months, month.name) : 'match' requires vector arguments

But this worked

aggregate(x, by = gsub("\\d\\d\\d\\d-(\\d\\d)-\\d\\d", "\\1", as.character(index(x))), mean)

Upvotes: 0

Related Questions