I have a dataframe showing a date, an item and a value, and I want to add a column showing the average of its 50 previous entries (or NA if it hasn't had 50) e.g. the table could be
data
date item value
01/01/01 a 2
01/01/01 b 1.5
04/01/01 c 1.7
05/01/01 a 1.9
......
and part of it could become
date item value last_50_mean
........
11/09/01 a 1.2 1.1638
12/09/01 b 1.9 1.5843
12/09/01 a 1.4 1.1621
13/09/01 c 0.9 NA
........
So in this case the mean of a in the 50 entries before 11/09/01 is 1.1638 and c hasn't had 50 entries before 13/09/01 so returns NA
I am currently doing this using the following function
data[, 'last_50_mean'] <- sapply(1:nrow(data), function(i){
prevDates <- data[data$date < data$date[i] & data$item == data$item[i], ]
num <- nrow(prevGames)
if(nGames >= 50){
round(mean(prevDates[(num- 49):num, ]$value), 4)
}
}
)
But my dataframe is large and it is taking a long time (in fact I'm not 100% sure it works as it is still running... Does anyone know of the best way to do this?