Silvia
Silvia

Reputation: 405

Extract column names with value 1 in binary matrix

I have a problem; i would like to create a new matrix starting from a binary matrix structured like this:

  A B C D E F
G 0 0 1 1 0 0
H 0 0 0 1 1 0
I 0 0 0 0 1 0
L 1 1 0 0 0 0

i want to create a new matrix made by row names of the starting one, and a new and unique column, called X, which contains for every rows, the name/names of the column every time the correspondent matrix number is 1.

How could i do?

Upvotes: 2

Views: 829

Answers (1)

989
989

Reputation: 12935

Try this where m is your matrix:

as.matrix(apply(m==1,1,function(a) paste0(colnames(m)[a], collapse = "")))

#  [,1]
#G "CD"
#H "DE"
#I "E" 
#L "AB"

Another option which might be faster if m is large:

t <- which(m==1, arr.ind = TRUE)
as.matrix(aggregate(col~row, cbind(row=rownames(t), col=t[,2]), function(x) 
                                                    paste0(colnames(m)[x], collapse = "")))

Upvotes: 1

Related Questions