This is a follow on question from Cumulative Mean with Grouping and Lag and Grouped moving average in r.
I'm looking to create a cumulative mean field with a lag of one that groups over multiple variables but is only calculating the average on certain criteria. So for the example below, S-AVG only gives the cumulative mean for S and vice versa for O-AVG and J-AVG. I'm sure this is possible using ave and cumsum, but am unsure how to do it.
Here is the desired output:
Player Goals **S-AVG** **O-AVG** **J-AVG**
S 5
S 2 5
S 7 3.5
O 3
O 9 3
O 6 6
O 3 3
S 7 4.66
O 1 5.25
S 7 5.25
S 3 5.6
Q 8 4.4
S 3 5.16
O 4 5
P 1 4.857
S 9 4.857
S 4 5.375
Z 6 4.375
S 3 5.22
O 8 4.55
S 3 5
O 4 4.9
O 1 4.81
S 9 4.81
S 4 5.16
O 6 4.5
J 6
Here is the data input for 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 appreciated.