I'm struggling to get the desired output using ddply. I believe I am on the right track but I think I am failing to output data from a loop, inside a loop...
Sample data:
Player, Career_Game, Date, ERA, Pitches
Gio Gonzalez, 176, Aug 1, 3.0, 86
Gio Gonzalez, 177, Aug 5, 4.01, 89
Gio Gonzalez, 178, Aug 10, 4, 11
Gio Gonzalez, 179, Aug 16, 4.06, 102
Gio Gonzalez, 180, Aug 21, 3.83, 97
...............
Jordan Zimmermann, 114, Apr 4, 1.8, 81
Jordan Zimmermann, 115, Apr 9, 8.1, 57
Jordan Zimmermann, 116, Apr 14, 5.27, 93
Jordan Zimmermann, 117, Apr 19, 3.92, 100
..............
Ill call this data frame, BB.
So what I am trying to accomplish is I want to get the average of the previous, lets say 5 games for each player at each instance... for example so far I have the code below....
Pitchers_5 = data.frame(ddply(BB, ~Player, tail, n=5, numcolwise(mean)))
This successfully calculates the previous five games for the Player (Career_Games 176 through 180). However, I would like to get this average for each observation. So for career_game 177, the code would calculate the mean for games 172 through 176, then spit out an instance for 177 having the mean of the previous 5 games then continue to instance 178, and recalculate the previous 5 games and so on... so using the data from above, once the code got to Gio Gonzalez 181st career game, it would look like this (the average of the previous 5 games)
Gio Gonzalez, 178, Date (Not necessary), 3.78, 77
UPDATE: Metrics comment has led me to look into the zoo package's rollmean function. I have since read a few posts and answers similar to my problem however am looking for further guidance (Rolling mean (moving average) by group/id with dplyr). This link resolves a very similar problem to mine except in 2 areas. It calculates the rolling mean of blood pressure by a unique ID into a new field, where I want to calculate the rolling mean of many fields. It also includes the blood pressure observation its on into its mean calculation. For example, Im looking for....
If I were to calculate the rolling means of Gio Gonzalez 180th game, I would want the mean of games 175 though 179. Not including the 180th game results.
Thanks!