【问题标题】:if previous value in one column and next value in another column meet a condition, add 1 into another column using r如果一列中的前一个值和另一列中的下一个值满足条件,则使用 r 将 1 添加到另一列
【发布时间】:2021-08-08 23:41:28
【问题描述】:

我有这样的数据

structure(list(id = c(1, 1, 2, 2, 2), time = c(1834, 4809, 18, 
333, 387), nh_source = c(0, 0, 1, 0, 0), admi_source = c(19, 
19, 85, 19, 88), disdest = c(85, 29, 56, 85, 39)), class = "data.frame", row.names = c(NA, 
-5L))

我想对 id 进行分组并检查 disdest 列中的前一个值是 56 还是 85,admisorc 列中的下一个值是 19,然后将 1 添加到列 nh_source 列。我希望 df 看起来像这样

structure(list(id2 = c(1, 1, 2, 2, 2), time = c(1834, 4809, 18, 
333, 387), nh_source2 = c(0, 1, 1, 1, 0), admi_source = c(19, 
19, 85, 19, 88), disdest = c(85, 29, 56, 85, 39)), class = "data.frame", row.names = c(NA, 
-5L))

【问题讨论】:

    标签: r data-wrangling


    【解决方案1】:

    在按'id'分组后用lag创建逻辑条件并将其添加到'nh_source'(TRUE -> 1 和FALSE -> 0)

    library(dplyr)
    df1 %>%
         group_by(id) %>% 
         mutate(nh_source = nh_source + 
                 (admi_source == 19 & lag(disdest) %in% c(56, 85))) %>%
         ungroup
    

    -输出

    # A tibble: 5 x 5
      id time nh_source admi_source disdest
    1  1 1834         0          19      85
    2  1 4809         1          19      29
    3  2   18         1          85      56
    4  2  333         1          19      85
    5  2  387         0          88      39
    

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      • 2021-08-25
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多