根据r中多个其他列的条件更新一列中的值

时间:2017-03-15 04:57:37

标签: r multiple-columns conditional-formatting

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. 创建名为1 year mortality

    的列

    如果Death_3monthsDeath_6monthsDeath_12 months = 1

    填写1,然后填写0

  2. 创建名为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

  3. 提前致谢

1 个答案:

答案 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