我有一个如下所示的数据框:
第二行显示患者入院后3小时和63小时的白蛋白实验室值。在这两行之间,我想添加59个新行,每次递增HoursFromAdmitLab
个值,因此我在入场后每小时有一行。对于第一行和第二行之间的59个新添加的行,我想重复每列的第一行值,除了我希望AbnormalityCode
和Value
为NA并且如前所述,{{1每行增加1。
所以我希望在入学后每小时有一行(HoursFromAdmitLab
),并且在实验室没有服用的时间内,我希望HoursFromAdmitLab
和Value
为NA,这意味着那里没有价值。我的结果数据框的第二行应如下所示:
我想在第二行和第三行之间重复此过程,依此类推。我尝试了一个循环,但它需要永远,我知道应该有一个更好的方法。
答案 0 :(得分:2)
实现此目的的一种可能方法是使用两个不同的连接:
data.table
包用于此,因为OP表明性能对他的设置至关重要。
library(data.table) # CRAN version 1.10.4
# make sure data is in correct order
setorder(setDT(DT), GUID, Hours)
# create sequence of hours for each case
Hours <- DT[, .(Hours = seq(min(Hours), max(Hours))), by = GUID]
# 1st join with columns which should not be filled
tmp <- DT[, c("GUID", "Hours", "Value", "AbnormCode")][Hours, on = c("GUID", "Hours")]
# 2nd, rolling join with columns which should be filled
result <- DT[, -c("Value", "AbnormCode")][tmp, on = .(GUID, Hours), roll = TRUE]
result
# GUID BirthYearNum GenderCode Hours Value AbnormCode
# 1: 27632200200 1949 Female 3 4.3 N
# 2: 27632200200 1949 Female 4 NA NA
# 3: 27632200200 1949 Female 5 NA NA
# 4: 27632200200 1949 Female 6 NA NA
# 5: 27632200200 1949 Female 7 NA NA
# ---
#273: 27632200200 1949 Female 275 NA NA
#274: 27632200200 1949 Female 276 NA NA
#275: 27632200200 1949 Female 277 NA NA
#276: 27632200200 1949 Female 278 NA NA
#277: 27632200200 1949 Female 279 3.0 L
请注意,该方法依赖于GUID
作为唯一键,即假设必须为每个GUID
创建单独的序列。
由于OP未能提供可重现的数据,因此使用以下数据:
library(data.table)
DT <- data.table(
GUID = "27632200200",
BirthYearNum = 1949L,
GenderCode = "Female",
Hours = c(3, 63, 111, 159, 231, 279),
Value = c(4.3, 3.8, 3.6, 3.3, 3, 3),
AbnormCode = c(rep("N", 3), rep("L", 3))
)
DT
# GUID BirthYearNum GenderCode Hours Value AbnormCode
#1: 27632200200 1949 Female 3 4.3 N
#2: 27632200200 1949 Female 63 3.8 N
#3: 27632200200 1949 Female 111 3.6 N
#4: 27632200200 1949 Female 159 3.3 L
#5: 27632200200 1949 Female 231 3.0 L
#6: 27632200200 1949 Female 279 3.0 L
请注意,HoursFromAdmitLab
缩写为Hours
,AbnormalityCode
缩写为AbnormCode
。