【问题标题】:Constructing variable lags based on additional condition根据附加条件构建变量滞后
【发布时间】: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


    【解决方案1】:

    我们可以通过取逻辑向量的累积和来创建一个基于'day_active'中存在1的分组列,然后if所有值都不为0,替换为NA并替换NAna.locf(来自zoo)、ungroup 的前一个非 NA 元素一起使用创建的列的lag

    library(dplyr)    
    da %>%
         group_by(grp = cumsum(day_active == 1)) %>%
         mutate(lag_n_wins = zoo::na.locf0(if(all(n_wins == 0)) n_wins 
                      else na_if(n_wins, 0)) ) %>%
         ungroup %>% 
         mutate(lag_n_wins = lag(lag_n_wins)) %>%
         select(-grp)
    # A tibble: 10 x 4
    #     day day_active n_wins lag_n_wins
    #   <dbl>      <dbl>  <dbl>      <dbl>
    # 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
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2023-02-07
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多