[R] Calculating rolling mean by group
Sam Albers
tonightsthenight at gmail.com
Tue Jan 10 00:39:42 CET 2012
Hello all,
I am trying to determine how to calculate rolling means in R using a
grouping variable. Say I have a dataframe like so:
dat1 <- data.frame(x = runif(2190, 0, 125), year=rep(1995:2000,
each=365), jday=1:365, site="here")
dat2 <- data.frame(x = runif(2190, 0, 200), year=rep(1995:2000,
each=365), jday=1:365, site="there")
dat <- rbind(dat1,dat2)
## What I would like to do is calculate a rolling 7 day mean
separately for each site. I have looked at both
## rollmean() in the zoo package and running.mean() in the igraph
package but neither seem to have led
## me to calculating a rolling mean by group. My first thought was to
use the plyr package but I am confused
## by this output:
library(plyr)
library(zoo)
ddply(dat, c("site"), function(df) return(c(roll=rollmean(df$x, 7))))
## Can anyone recommend a better way to do this or shed some light on
this output?
Thanks so much in advance!
Sam
More information about the R-help
mailing list