我有一个包含 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