R在矩阵中的条件下检索列名称

时间:2013-05-03 08:36:46

标签: r matrix conditional-statements

我有一个0或1值的矩阵。当一行只有一个“1”时,我想得到的列名是“1”值,在任何其他情况下得到“0”。对于以下示例:

test <- matrix(c(0,1,0,1,0,0,1,0,1,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0),ncol=5)
colnames(test) <- c('c1','c2','c3','c4','c5')

结果应该是:

     c1 c2 c3 c4 c5 result
[1,]  0  1  1  0  1 0
[2,]  1  0  0  0  0 c1
[3,]  0  0  0  1  0 c4
[4,]  1  0  1  0  1 0
[5,]  0  1  0  0  0 c2
[6,]  0  0  0  1  1 0
[7,]  1  0  0  0  0 c1
[8,]  0  0  1  0  0 c3

1 个答案:

答案 0 :(得分:1)

你去了:

test <- matrix(c(0,1,0,1,0,0,1,0,1,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0),ncol=5)
colnames(test) <- c('c1','c2','c3','c4','c5')

result <- data.frame(test, result = apply(test, 1, function(row){ if(sum(row)==1)colnames(test)[[which(row==1)]]else 0}))