I'm looking to create a cumulative mean that averages over multiple groups with a lag. It is for predictive analysis so I want each row to be the cumulative mean of all the rows before it (not including its own value).
This is a follow on from Grouped moving average in r
I'm sure there is a way to do this with rollapply and ave, I have been achieving this result with various moving windows using the below(just not a cummean):
library(zoo)
roll <- function(x, n) {
if (length(x) <= n) NA
else rollapply(x, list(-seq(n)), mean, fill = NA)
}
transform(DF, AVG2 = ave(Goals, Player, FUN = function(x) roll(x, 2)),
AVG3 = ave(Goals, Player, FUN = function(x) roll(x, 3)))
Here is the desired output:
Player Goals **AVG**
S 5
S 2 5
S 7 3.5
O 3
O 9 3
O 6 6
O 3 6
S 7 4.66
O 1 5.25
S 7 5.25
S 3 5.6
Q 8
S 3 5.16
O 4 4.4
P 1
S 9 4.857
S 4 5.375
Z 6
S 3 5.22
O 8 4.33
S 3 5
O 4 4.857
O 1 4.75
S 9 4.81
S 4 5.16
O 6 4.33
J 6
and here is the code to recreate the initial table in r
Player <- c('S','S','S','O','O','O','O','S','O','S','S','O','S','O','O','S','S','O','S','O','S','O','O','S','S','O','J')
Goals <- c(5,2,7,3,9,6,3,7,1,7,3,8,3,4,1,9,4,6,3,8,3,4,1,9,4,6,6)
data.frame(Player, Goals)
Any help is much appreciated