创建事件起始变量

Creating Event Onset Variable

我有临床数据,记录了患者在三个时间点的疾病结果,由一个二元变量表示。看起来像这样

patientid <- c(100,100,100,101,101,101,102,102,102)
time <- c(1,2,3,1,2,3,1,2,3)
outcome <- c(0,1,1,0,0,1,1,1,0) 

Data<- data.frame(patientid=patientid,time=time,outcome=outcome)
Data

我想创建一个起始变量,因此对于每个患者,它将为患者首次患病的时间编码为 1,但之后的任何时间段或之后的时间段都将编码为 0 (即使那个病人仍然患有这种疾病)。对于示例数据,它现在应该如下所示。

patientid <- c(100,100,100,101,101,101,102,102,102)
time <- c(1,2,3,1,2,3,1,2,3)
outcome <- c(0,1,1,0,0,1,1,1,0) 
outcome_onset <- c(0,1,0,0,0,1,1,0,0)

Data<- data.frame(patientid=patientid,time=time,outcome=outcome, 
outcome_onset=outcome_onset)
Data

因此我想要一些代码/一些帮助来自动创建 outcome_onset 变量。

这里有一个 cumsum 的选项,用于在按 'patientid'

分组后创建逻辑向量
library(dplyr)
Data %>% 
   group_by(patientid) %>%
   mutate(outcome_onset = +(cumsum(outcome) == 1))

或使用match%in%

Data %>%
   group_by(patientid) %>% 
   mutate(outcome_onset = +(row_number() %in% match(1, outcome_onset)))

我们可以使用 which.max 获取 outcome 变量中第一个的索引,并将该行设为 1,其余行设为 0。

library(dplyr)

Data %>%
  group_by(patientid) %>%
  mutate(outcome_onset = as.integer(row_number() %in% which.max(outcome)), 
         outcome_onset = replace(outcome_onset, is.na(outcome), NA))

#  patientid  time outcome outcome_onset
#      <dbl> <dbl>   <dbl>         <int>
#1       100     1       0             0
#2       100     2       1             1
#3       100     3       1             0
#4       101     1       0             0
#5       101     2       0             0
#6       101     3       1             1
#7       102     1       1             1
#8       102     2       1             0
#9       102     3       0             0