Apply a rolling sum by group in R
<p>I need to calculate a rolling sum by group.</p>

<pre><code>y&lt;- 1:10
tmp&lt;-data.frame(y)
tmp$roll&lt;-NA
tmp$roll[2:10]&lt;-rollapply (y, 2, sum)
tmp$g&lt;-(c("a","a","a","a","a","b","b","b","b","b"))
</code></pre>

<p><code>tmp$roll</code> calculates the rolling sum for <code>tmp$y</code>; I need to do this by <code>tmp$g</code>. 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 <code>a</code> and <code>b</code> (this a simplified example of actual data frame):</p>

<pre><code>roll_group
NA 
3
5
7
9
NA
13
15
17
19
</code></pre>