r如何根据所有行的

时间:2017-03-09 10:15:07

标签: r

我想创建一个变量,它为每一行连接我们拥有TRUE模态的列名。

我试过

names(mat2)[mat2[i,]==TRUE]

但它不起作用。 以下是我的数据:

# dput(data)
structure(list(Object1 = c(FALSE, FALSE, FALSE, FALSE, FALSE, 
TRUE, TRUE, TRUE, TRUE, TRUE), Object2 = c(FALSE, FALSE, FALSE, 
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), Object3 = c(FALSE, 
FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE), Object4 = c(FALSE, 
FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), 
    Object5 = c(FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, 
    FALSE, FALSE, FALSE), Object6 = c(FALSE, FALSE, TRUE, FALSE, 
    FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), Object7 = c(FALSE, 
    FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE
    ), Object8 = c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 
    FALSE, FALSE, FALSE, FALSE), Object9 = c(FALSE, FALSE, FALSE, 
    TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), Object10 = c(FALSE, 
    FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE), 
    Object11 = c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 
    FALSE, FALSE, FALSE), Object12 = c(FALSE, FALSE, TRUE, FALSE, 
    FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), Object13 = c(FALSE, 
    TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE
    ), Object14 = c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, 
    TRUE, TRUE, TRUE, TRUE), Object15 = c(FALSE, FALSE, FALSE, 
    FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE), Object16 = c(FALSE, 
    FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE
    )), .Names = c("Object1", "Object2", "Object3", "Object4", 
"Object5", "Object6", "Object7", "Object8", "Object9", "Object10", 
"Object11", "Object12", "Object13", "Object14", "Object15", "Object16"
), row.names = c(NA, 10L), class = "data.frame")

这里我的数据框有颜色(我为TRUE模态设置了1种颜色):

enter image description here

我想获得一个像这样的新变量:

enter image description here

1 个答案:

答案 0 :(得分:2)

我们可以将applyMARGIN = 1

一起使用
data$NewColumn <- apply(data, 1, FUN = function(x) paste(names(x)[x], collapse=' '))