Cumulative sums, moving averages, and SQL “group by” equivalents in R
What's the most efficient way to create a moving average or rolling sum in R? How do you do the rolling function along with a "group by"? While zoo is great, sometimes there are simpler ways. If you data behaves nicely, and is evenly spaced, the embed() function effectively lets you create multiple lagged version of a time series. If you look inside the VARS package for vector auto-regression, you will see that the package author chooses this route. For example, to calculate the 3 period rolling average of x, where x = (1 -> 20)^2: > x <- (1:20)^2 > embed (x, 3) [,1] [,2] [,3] [1,] 9 4 1 [2,]