Fierce82
Fierce82

Reputation: 408

Indexing elements in matrix and corresponding column numbers

I have a matrix full of integers and I need to create an index where for each of these integers I get the numbers of columns containing it (using R).

For instance, 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 being present in columns: 1,2 and 4

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

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

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

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

etc

edit: i corrected my mistake pointed out in comment bellow.

Upvotes: 3

Views: 73

Answers (1)

akrun
akrun

Reputation: 887108

We can do

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

Or another option is

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

Upvotes: 3

Related Questions