Indexing elements in a matrix and corresponding column numbers

I have a matrix full of integers and I need to create an index where, for each of those integers, I get the number of columns that contain it (using R).

For example, suppose I have this table:

              [,1]       [,2]       [,3]       [,4]       [,5]       [,6]       
   [1,] 31738      3136023010  777150982 2318301701         44 3707934113 
   [2,] 1687741813         44  31738     1284682632  462137835  445275140  
   [3,]         44        123        123 31738      1215490197       123 

      

In my case, I have 31738 present in columns: 1,2 and 4

: [1,1], [2,3] and [3,4]

and 44 are present in columns 1, 2 and 5 (elements [3,1], [2,2] and [1,5]

So, for all the elements in my table, I need an index like

31738      = 1 3 4
3136023010 = 2
777150982  = 3
44         = 1 2 3
....
123        = 2 3 6

      

etc.

edit: I've fixed the error mentioned in the comment below.

+3


source to share


1 answer


We can do it

setNames(lapply(unique(m1), function(i) 
     as.vector(which(m1==i, arr.ind = TRUE)[,2])), unique(m1)) 

      


Or another option



split(col(m1), m1)

      

data

m1 <- structure(c(31738, 1687741813, 44, 3136023010, 44, 123, 777150982, 
31738, 123, 2318301701, 1284682632, 31738, 44, 462137835, 1215490197, 
3707934113, 445275140, 123), .Dim = c(3L, 6L))

      

+3


source







All Articles