[英]Lead/lag in R but only for rows that meet a yes/no condition
我有一個患者就診數據集,如下所示:
visit infection treatment
1 1 negative 1
2 2 negative 1
3 3 positive 1
4 4 negative 0
5 5 positive 1
6 6 positive 0
7 7 positive 1
8 8 negative 0
9 9 negative 1
10 10 negative 1
11 11 negative 0
12 12 positive 1
13 13 positive 1
我想創建一個列, treatment_second_neg_visit
,它告訴我患者是否在手頭就診后的第二次感染陰性就診中接受了治療(如果兩次感染陰性就診未在手頭就診之后進行,則為NA
)。 基本上,領先/落后,但僅在滿足特定條件時。
注意:即使對於感染陽性的行,我仍然對隨后的第二次感染陰性訪問感興趣。
示例 1:對於第一次訪問(第 1 行),下一次否定訪問是第 2 行,第二次否定訪問是第 4 行,其中治療 = 0。 因此,對於第 1 行, treatment_second_neg_visit
的值應為 0。
示例 2:對於第二次訪問(第 2 行),下一次否定訪問是第 4 行,第二次否定訪問是第 8 行,其中治療 = 0。 因此,對於第 2 行, treatment_second_neg_visit
的值應為 0。
最終的 output 應該是:
visit infection treatment treatment_second_neg_visit
1 negative 1 0
2 negative 1 0
3 positive 1 0
4 negative 0 1
5 positive 1 1
6 positive 0 1
7 positive 1 1
8 negative 0 1
9 negative 1 0
10 negative 1 NA
11 negative 0 NA
12 positive 1 NA
13 positive 1 NA
創建數據集的代碼:
dat <- data.frame(visit = 1:13, infection = c("negative", "negative", "positive", "negative", "positive", "positive", "positive", "negative", "negative", "negative", "negative", "positive", "positive"), treatment = c(1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1))
基礎 R 或 dplyr 是理想的,但對任何正確的解決方案都持開放態度。
1)首先創建一個列neg
,它給出了到目前為止的否定數,然后在指定的條件下執行左自連接。
library(sqldf)
dat2 <- transform(dat, neg = cumsum(infection == 'negative'))
sqldf("select a.visit, a.infection, a.treatment, b.treatment second
from dat2 a
left join dat2 b on a.neg + 2 = b.neg and b.infection = 'negative' ")
給予:
visit infection treatment second
1 1 negative 1 0
2 2 negative 1 0
3 3 positive 1 0
4 4 negative 0 1
5 5 positive 1 1
6 6 positive 0 1
7 7 positive 1 1
8 8 negative 0 1
9 9 negative 1 0
10 10 negative 1 NA
11 11 negative 0 NA
12 12 positive 1 NA
13 13 positive 1 NA
或者我們可以在一個 sql 語句中完成所有操作:
sqldf("with dat2 as (
select *, sum(infection = 'negative') over (rows unbounded preceding) neg
from dat
)
select a.visit, a.infection, a.treatment, b.treatment second
from dat2 a
left join dat2 b on a.neg + 2 = b.neg and b.infection = 'negative' ")
2) dplyr dat2
是帶有附加列的dat
,它給出了當前行(包括當前行)的負數。 然后我們執行指示的左連接。
library(dplyr)
dat2 <- dat %>%
mutate(neg = cumsum(infection == 'negative'))
dat2 %>%
mutate(neg = neg + 2) %>%
left_join(filter(dat2, infection == 'negative'), "neg", suffix = c("", ".y")) %>%
select(visit, infection, treatment, second = treatment.y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.