R Retrieve column name under condition in a matrix -


i have matrix 0 or 1 values. when line has 1 "1", want in return column name in "1" value , in other cases "0". example below:

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 should be:

     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 

there go:

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})) 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -