我想创建一个新变量,它是partiucular userID的3个月平均值。
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
示例,第10行(对应于用户“a”)的新变量的值为mean(10 + 7 + 4) = 7
。
我怎么能这样做?理想情况下,在tidyverse / dplyr。