I would like to create a new variable that is the 3 month average for a partiucular userID.
df <- data.frame(
dates = seq(as.Date('2018-01-01'), as.Date('2018-12-01'), by = "month"),
user_id = c("a","b","c","a","b","c","a","b","c","a","b","c"),
somenum = 1:12
)
df
dates user_id somenum
1 2018-01-01 a 1
2 2018-02-01 b 2
3 2018-03-01 c 3
4 2018-04-01 a 4
5 2018-05-01 b 5
6 2018-06-01 c 6
7 2018-07-01 a 7
8 2018-08-01 b 8
9 2018-09-01 c 9
10 2018-10-01 a 10
11 2018-11-01 b 11
12 2018-12-01 c 12
Example, the new variable, on row 10 (corresponding to user "a") would have a value of mean(10 + 7 + 4) = 7
.
How could I do this? Ideally in tidyverse/dplyr.