Annual group means with uneven groups in dplyr?

Viewed 119

Say I have the following data:

library(dplyr)
year <- rep(c(1,2,2,3,4,4,5),3)
group <- c(rep(1,7),rep(2,7),rep(3,7))
v1 <- rep(c(0,1,2,3,4,5,6),3)
v2 <- rep(c(1,2,3,4,5,6,7),3)
df <- data.frame(year,group,v1,v2)

I would like rolling annual group means for each variable, so that I end up with unique group-year means that take all previous years into account.

I know that this will give me annual group means:

gm <- df %>% 
    group_by(group, year) %>% 
    summarise_each(funs(mean))

But this doesn't consider all previous years. I need each group-year to include all previous group-years, and (importantly) the length of each group-year is ragged, so I cannot just take annual means and then group_by() each group and do a rolling mean over annual means.

1 Answers
Related