Here is an example of my data:
id score
1 82 0.50000
2 82 0.39286
3 82 0.56250
4 328 0.50000
5 328 0.67647
6 328 0.93750
7 328 0.91667
I want to make a column of moving average's of scores for each id.
So I need to somehow group the data by id then apply a MA function to that grouped data and then have the output as another column "MA_score"
I would like my output to look like this:
id score MA_score
1 82 0.50000 NULL
2 82 0.39286 0.xxxx
3 82 0.56250 NULL
4 328 0.50000 NULL
5 328 0.67647 0.yyyy
6 328 0.93750 0.qqqq
7 328 0.91667 NULL
You could use split and rollapply from the zoo package as one of many ways to approach this. Note that in the example below I set the width of the rollapply function to 1 so it just returns each value. For widths greater than one it will take the mean of that number of values.
If we were to set
width = 3
you would get:Or you could use aggregate in
base
R:There are quite a few ways to do this. I would precisely define your moving average function though, because there are many ways to calculate it (check out for example
TTR:::SMA
)Or more straightforward using
ave
:You could split your data by unique ID values, calculate the rolling mean (from 'zoo' package) for each of these unique IDs and append the results to your initial dataframe: