有条件地用列名填充数据表

时间:2020-01-22 08:28:11

标签: data.table conditional-statements fill col

你好,我想这个问题对于R专家来说很容易。我需要用列名填充数据表。填充取决于另一个色谱柱条件。例子:

library(data.table)
dt <- data.table(V1=1:12, V2=c(1L,0L), V3=c(0L,1L,0L))

enter image description here

我要获取的表是:

enter image description here

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

一些选项:

1)使用for

cols <- c("V2", "V3")
for (x in cols)
    set(dt, dt[get(x)==1L, which=TRUE], paste0(x,".twin"), x)

2)在i中进行子设置,然后按引用进行更新

for (x in cols)
    dt[get(x)==1L, paste0(x,".twin") := x]

3)为向量建立索引

cols <- c("V2", "V3")
dt[, paste0(cols, ".twin") := Map(function(x, nm) c(NA_character_, nm)[x+1L], .SD, cols), .SDcols=cols]

4)使用ifelse

dt[, paste0(cols, ".twin") := Map(function(x, nm) fifelse(x==1L, nm, NA_character_), .SD, cols), .SDcols=cols]

输出:

    V1 V2 V3 V2.twin V3.twin
 1:  1  1  0      V2    <NA>
 2:  2  0  1    <NA>      V3
 3:  3  1  0      V2    <NA>
 4:  4  0  0    <NA>    <NA>
 5:  5  1  1      V2      V3
 6:  6  0  0    <NA>    <NA>
 7:  7  1  0      V2    <NA>
 8:  8  0  1    <NA>      V3
 9:  9  1  0      V2    <NA>
10: 10  0  0    <NA>    <NA>
11: 11  1  1      V2      V3
12: 12  0  0    <NA>    <NA>
相关问题