Cumulative sums, moving averages, and SQL "group by" equivalents in R -
What is the most effective way to create a moving average or rolling sum in R? How do you do the rolling function with "group"?
While the zoo is very good, sometimes there are simple ways if you deal with data well , And evenly keep the difference, the embed () function effectively lets you create multiple legions versions of a time series. If you look for vector auto-retression in the VARS package, you will see that the package author chooses this route. For example, to calculate 3 times the rolling average of x, where x = (1 -> 20) ^ 2:
& gt; X & LT; - (1:20) ^ 2 & gt; Embed [X, 3] [, 1] [, 2] [, 3] [1,] 9 4 1 [2,] 16 9 4 [3,] 25 16 9 [4], 36 25 16 [5,] 49 36 25 [6,] 64 49 36 [7,] 81 64 49 [8,] 100 81 64 [9,] 121 100 81 [10,] 144 121 100 [11,] 169 144 121 [12,] 196 16 9 144 [13,] 225 196 16 9 [14,] 286 256 225 [15,] 324 28 9 256 [17,] 361 324 28 9 [18,] 400 361 324 & gt; (1 (x, 3), 1, mean) [1] 4.666667 9.666667 16.666667 25.666667 36.666667 49.666667 [7] 64.666667 81.666667 100.666667 121.666667 144.666667 16 9.666667 [13] 19666667 225.666667 256.666667 289.666667 324.666667 361.666667 361.666667
Comments
Post a Comment