Fernando
Fernando

Reputation: 7905

Extract month mean from time series in R

I have some data in the following format:

    date     x     
    2001/06  9949 
    2001/07  8554  
    2001/08  6954 
    2001/09  7568 
    2001/10 11238  
    2001/11 11969 
    ... more rows

I want to extract the x mean for each month. I tried some code with aggregate, but failed. Thanks for any help on doing this.

Upvotes: 1

Views: 1141

Answers (2)

Sacha Epskamp
Sacha Epskamp

Reputation: 47642

Here I simulate a data frame called df with more data:

df <- data.frame( 
      date = apply(expand.grid(2001:2012,1:12),1,paste,collapse="/"),
      x = rnorm(12^2,1000,1000),
      stringsAsFactors=FALSE)

Using the way your date vector is constructed you can obtain months by removing the firs four digits followed by a forward slash. Here I use this as indexing variable in tapply to compute the means:

with(df, tapply(x, gsub("\\d{4}/","",date), mean))

Upvotes: 1

Fernando
Fernando

Reputation: 7905

Sorry...just creat an month-sequence vector then used tapply. It was very easy:

m.seq = rep(c(6:12, 1:5), length = nrow(data))
m.means = tapply(data$x, m.seq, mean)

But thanks for the comments anyway!

Upvotes: 0

Related Questions