I have a csv file of every golf score recorded by player, tournament, and date, and I want to create a column that calculates the average of the past 50 scores BY player using the date field. It needs to be running average by Player.
example: Table
PLAYER,SCORE,Tournament,ROUNDDATE,Observation,ID
Matthew Fitzpatrick,60,KLM Open,42258,1,1
Jaco Van Zyl,61,Turkish Airlines Open,42306,1,2
Paul Lawrie,61,KLM Open,42257,1,3
Wade Ormsby,61,KLM Open,42257,1,4
Callum Shinkwin,62,Shenzhen International,42483,1,5
Danny Willett,62,Omega European Masters,42209,1,6
Joakim Lagergren,62,Alfred Dunhill Links Championship,42280,1,7
I have tried this code but it just produces the exact same result and not an average of anything
get.mav <- function(bp,n=50){
require(zoo)
if(is.na(bp[1])) bp[1] <- mean(bp,na.rm=TRUE)
bp <- na.locf(bp,na.rm=FALSE)
if(length(bp)<n) return(bp)
c(bp[1:(n-1)],rollapply(bp,width=n,mean,align="right"))
}
test <- with(test,test[order(PLAYER,ROUNDDATE),])
test$SCORE_UPDATED <-
unlist(aggregate(SCORE~PLAYER,test,get.mav,na.action=NULL,n=50)$SCORE)
test