I have kids' personal best times listed per week per stroke. For kid A, how can I calculate that kid's means for all previous weeks, excluding current week's results? For example, one kid's results might look like this:
df.trial <- data.frame(Week= c("w10", "w9", "w9", "w5", "w5", "w5", "w6", "w6", "w3"), Stroke= c("Fly","Free","Breast","Back","Free","Breast","Fly","Back","Free"), Score = c(5.5,4.5,4.6,5.2, 4.3, 5.7, 4.7,5.5,4.8))
I'm trying to add a new column to calculate the means like this:
df.desired <- data.frame(Week= c("w10", "w9", "w9", "w5", "w5", "w5", "w6", "w6", "w3"), Stroke= c("Fly","Free","Breast","Back","Free","Breast","Fly","Back","Free"), Score = c(5.5, 4.5, 4.6, 5.2, 4.3, 5.7, 4.7, 5.5, 4.8), prev.mean = c(4.91, 5.03, 5.03, 4.80, 4.80, 4.80, 5.00, 5.00, NA))
The data I have has lots of kids so I will need to group by each student's name. Also, if there are no previous weeks then I'd like to add an NA.
I have tried a few different ways and have tried to write a function like the rollsum one described here: R previous week total
No luck so far. Any suggestions please?