Search code examples
rmatrixcell

Find the position of a cell in a matrix from the content


Very basic question but I can't find an answer.

For a generic matrix (in my case I have an adjacency matrix like the following one, but much bigger):

   A B C D E 
A  0 1 0 2 1 
B  0 0 1 0 0 
C  0 1 0 1 0 
D  0 1 1 0 0 
E  0 0 0 1 0 

I computed the frequency of values in the adjacency matrix

table <- data.frame(table(as.matrix(n)))

and I'd like now to know how to understand where those values come from.

Basically, I know the value of a cell, how do I find its position within the matrix?

I don't know how the output would look like, I just need number of row and column, or names of them.


Solution

  • Arbitrary adjacency matrix n:

    n <- as.matrix(rbind(c(1,0.2,0.8,0.6),
                    c(0.3,1,0.8,0.2),
                    c(0.8,0.1,1,0.3),
                    c(0.8,0.2,0.3,1)))
    

    Find position of 0.8's.

    value = 0.8
    which(n == value, arr.ind=T)
    

    Output:

         row col
    [1,]   3   1
    [2,]   4   1
    [3,]   1   3
    [4,]   2   3