【发布时间】: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。
treatment 和 previous_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 开头的条纹。
提前非常感谢
【问题讨论】: