对每位患者的变量进行首次观察

Carry Forward First Observation for a Variable For Each Patient

我的数据集有 3 个变量:

Patient ID    Outcome     Duration  
1               1          3
1               0          4
1               0          5
2               0          2
3               1          1
3               1          2

我想要的是 "Duration" 对每个患者 ID 的第一次观察。

也就是说,对于患者 #1,我希望持续时间读取 3、3、3 对于患者 #3,我希望持续时间读取 1、1。

这是 data.table 的一种方式。你取 Duration 中的第一个数字,并要求 R 为每个 PatientID.

重复它
mydf <- read.table(text = "PatientID    Outcome     Duration  
1               1          3
1               0          4
1               0          5
2               0          2
3               1          1
3               1          2", header = T)

library(data.table)
setDT(mydf)[, Duration := Duration[1L], by = PatientID]
print(mydf)

#   PatientID Outcome Duration
#1:         1       1        3
#2:         1       0        3
#3:         1       0        3
#4:         2       0        2
#5:         3       1        1
#6:         3       1        1

另一种使用 plyr 的替代方法(如果您要对数据框进行大量操作,特别是如果它很大,我建议使用 data.table。它的学习曲线更陡峭,但非常值得它)。

library(plyr)
ddply(mydf, .(PatientID), transform, Duration=Duration[1])  PatientID 
# Outcome Duration
# 1         1       1        3
# 2         1       0        3
# 3         1       0        3
# 4         2       0        2
# 5         3       1        1
# 6         3       1        1

这对 dplyr 来说是个好工作(plyr 的 data.frame 更邪恶的继任者,语法比 data.table 好得多):

library(dplyr)

dat %>% 
  group_by(`Patient ID`) %>% 
  mutate(Duration=first(Duration))

## Source: local data frame [6 x 3]
## Groups: Patient ID
## 
##   Patient ID Outcome Duration
## 1          1       1        3
## 2          1       0        3
## 3          1       0        3
## 4          2       0        2
## 5          3       1        1
## 6          3       1        1