0

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.

Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • Your example is not using the 3 month average though. If the current month is 10 with value 10, you go back to month 4 with value 4. Am I missing something? – AntoniosK Jun 08 '18 at 15:49
  • 1
    @AntoniosK it's the average of the most recent 3 months that I'm seeking, including the current month. The linked duplicate answer seems to do the trick though. – Doug Fir Jun 08 '18 at 15:51

0 Answers0