I need to calculate a rolling sum by group.
y<- 1:10
tmp<-data.frame(y)
tmp$roll<-NA
tmp$roll[2:10]<-rollapply (y, 2, sum)
tmp$g<-(c("a","a","a","a","a","b","b","b","b","b"))
tmp$roll
calculates the rolling sum for tmp$y
; I need to do this by tmp$g
. I think I may need to split the data frame into a list of data frames by group and then bind back together but this seems like a long route. The result would be an additional column of the rolling sum by group a
and b
(this a simplified example of actual data frame):
roll_group
NA
3
5
7
9
NA
13
15
17
19