I'm trying to take the moving average of a players fantasy points, based on their past performance against the same hand pitcher, over the past 3 games.
FP <- data.frame(player = c(rep("A",10), rep("B",10), rep("C",10)),
pitcher_hand = rep(c("R","L"),15),
fantasy_points = runif(30, min = 0, max = 25))
I know i can use rollapplyr from (zoo) to take moving averages, but here I need the conditional moving average, based on another column. For instance, the new column moving average for row 7 would be the average fantasy points for row 5, 3, and 1, since it was against the same handed pitcher. I've tried:
FP <- FP %>%
group_by(player) %>%
mutate(FP_L3 = rollapplyr(.,list(-(3:1)),function(x) mean(x[x[['pitcher_hand']]==pitcher_hand]),fill=NA))
How can this be done? I can do this in a big loop, iterating through every row in my dataframe and searching for correct matches, however I want to avoid this since my dataframe is quite large.