【问题标题】:Deleting rows based on a condition multiple observations before根据之前的多个观察条件删除行
【发布时间】:2022-01-09 23:55:00
【问题描述】:

我已经挣扎了一段时间了,我只是错过了一步。我希望你能帮助完成这最后一步。

Reprex

structure(list(record_id = c(110001, 110001, 110001, 110001, 
110001, 110001, 110001, 110001, 110001, 110021, 110021, 110021, 
110021, 110021, 110021, 110021, 110021, 110021, 110021, 110021, 
110021, 110021), day_count = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 
2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), previous_treatment = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
), treatment = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0), interruption_streak = c(1, 2, 3, 4, 5, 
6, 7, 8, 9, 1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), row.names = c(NA, 
-22L), groups = structure(list(record_id = c(110001, 110021), 
    .rows = structure(list(1:9, 10:22), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

说明

这只是主要数据集的摘录,我在其中列出了每位参与者每天的治疗方式。

在这里,您可以看到两个研究参与者record_id 110001 和 110021

为了计算他们的治疗中断了多少天,我创建了一个 count_streak 函数interruption_streak

这是treatment的函数:如果treatment = 0,则开始计数直到treatment > 0。

treatmentprevious_treatment 都可以是 0(不处理)或 1,2,3(处理 A、B、C)

但是,正如您在 record_id 110001 中看到的那样,您不能真正将第一次连续称为中断,因为在第 1 天之前,他根本没有接受任何治疗previous_treatment = 0。同样适用于第一连胜 110021。

第二个连续 110021 是唯一有效的,我想将其视为中断并保留在数据集中: 在第 5 天,它从 previous_treatment = 1 变为 treatment = 0。

问题

我想删除所有以previous_treatment = 0 开头的条纹,并保留所有以previous_treatment > 0 开头的条纹。

提前非常感谢

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    你很亲密。够了吗?

    df %>% group_by(record_id) %>% 
      filter(cumsum(previous_treatment) > 0)
    
       record_id day_count previous_treatment treatment interruption_streak
           <dbl>     <dbl>              <dbl>     <dbl>               <dbl>
     1    110021         5                  1         0                   1
     2    110021         6                  0         0                   2
     3    110021         7                  0         0                   3
     4    110021         8                  0         0                   4
     5    110021         9                  0         0                   5
     6    110021        10                  0         0                   6
     7    110021        11                  0         0                   7
     8    110021        12                  0         0                   8
     9    110021        13                  0         0                   9
    10    110021        14                  0         0                  10
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 2016-11-16
      • 1970-01-01
      • 2022-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      相关资源
      最近更新 更多