2

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?

989
  • 12,579
  • 5
  • 31
  • 53
Silvia
  • 405
  • 4
  • 17
  • See [this similar post](https://stackoverflow.com/questions/36304404/create-a-new-column-with-non-null-columns-names) – alexis_laz Jun 16 '17 at 11:03

1 Answers1

1

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 = "")))
989
  • 12,579
  • 5
  • 31
  • 53
  • 1
    I tested the time taken for a matrix of dim `1e+5 x 100` and the first approach is much faster. – 989 Jun 16 '17 at 15:55