【发布时间】:2020-04-25 19:27:34
【问题描述】:
我想根据以下附加条件和操作创建一个滞后变量:
当变量(day_active)的lag(上一行)为1时,也要取变量n_wins的lag
当day_active的lag(上一行)为0时,只要day_active保持为0,就应该重复上一行的n_wins的值。
假设我们观察一个玩家十天。 day_active 表示他当天是否活跃,n_wins 表示他赢得的比赛数。
Example dataset:
da = data.frame(day = c(1,2,3,4,5,6,7,8,9,10), day_active = c(1,1,0,0,1,1,0,0,1,1), n_wins = c(2,3,0,0,1,0,0,0,0,1))
da
day day_active n_wins
1 1 1 2
2 2 1 3
3 3 0 0
4 4 0 0
5 5 1 1
6 6 1 0
7 7 0 0
8 8 0 0
9 9 1 0
10 10 1 1
这就是它在转换后的样子:
da2 = data.frame(day = c(1,2,3,4,5,6,7,8,9,10), day_active = c(1,1,0,0,1,1,0,0,1,1), n_wins = c(2,3,0,0,1,0,0,0,0,1), lag_n_wins = c(NA,2,3,3,3,1,0,0,0,0))
da2
day day_active n_wins lag_n_wins
1 1 1 2 NA
2 2 1 3 2
3 3 0 0 3
4 4 0 0 3
5 5 1 1 3
6 6 1 0 1
7 7 0 0 0
8 8 0 0 0
9 9 1 0 0
10 10 1 1 0
【问题讨论】:
标签: r dplyr conditional-statements transform tidyr