R版本3.3.2(2016-10-31)
R Studio版本1.0.136
平台:X86_64-apple-darwin13.4.0(64位)
数据框
Subject Drug Death_3MONTHS, Death_6MONTHS, Death_12MONTHS
1 1 0 0 NaN
2 1 1 NaN NaN
3 2 0 0 0
4 2 0 0 1
NaN
- 缺失值=失去跟进
问题
我想创建另外两列
创建名为1 year mortality
如果Death_3months
,Death_6months
或Death_12 months = 1
,
填写1
,然后填写0
创建名为Time to Event
如果Death_3months
= NaN
填充0
如果Death_3months
= 1
填充3
,
如果Death_3months
= 0
请检查Death_6months
列
如果Death_6months
= NaN
填充3
如果Death_6months
= 1
填充6
,
如果Death_6months
= 0
请检查Death_12months
列
如果Death_12months
= NaN
填充6
如果Death_12months
= 1
填充12
,
如果Death_12months
= 0
填写12
提前致谢
答案 0 :(得分:0)
使用data.table包的解决方案:
library(data.table)
#initilize sample data.table
DT <- data.table(c(1,2,3,4), c(1,1,2,2),c(0,1,0,0),c(0,NaN,0,0),c(NaN,NaN,0,1))
colnames(DT) <- c("Subject","Drug","Death_3Months","Death_6months","Death_12months")
#Add row together using death columns and exclude NA's
DT[, "1 year mortality" := rowSums(.SD, na.rm=TRUE), .SDcols = 3:5]
#run through ifelse logic as described
DT[, "Time to Event" := ifelse(!is.finite(Death_3Months), 0,
ifelse(Death_3Months == 1, 3,
ifelse(!is.finite(Death_6months), 3,
ifelse(Death_6months == 1, 6,
ifelse(!is.finite(Death_12months), 6, 12)))))]
DT
> DT
Subject Drug Death_3Months Death_6months Death_12months 1 year mortality Time to Event
1: 1 1 0 0 NaN 0 6
2: 2 1 1 NaN NaN 1 3
3: 3 2 0 0 0 0 12
4: 4 2 0 0 1 1 12