R Retrieve column name under condition in a matrix

I have a matrix with 0 or 1 values. When a line has only one "1", I want to get in return the column name in which is the "1" value and in any other cases get "0". For the 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

Answers


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

Need Your Help

When making an if statement can I make it so a void that is already running be overwritten?

ios objective-c

I have a bug with my game about red circle, blue circle, and yellow circle. You can only touch the red circle. I have a random button selector that I called buttonChanger. Whenever this method is r...

In android Why my ProgressBar Freezes?

android progress-bar

i am showing Progress Bar at time of retrieving data from server and after retrieving data from server showing that data on chart but at time of plotting that data on chart my progress bar get free...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.