rarraysmatrixindexing

Get column and row position of nth element in a matrix


Say I have a 10 x 10 two dimensional matrix...

set.seed(1)

mat <- matrix(sample(1:10,size=100,replace = T), ncol = 10)

How would I access the column and row position of the 83rd element in this matrix? It's easy enough to extract the element itself...

mat[83]

But I need the column and row position.


Solution

  • You can use arranyInd with dim(mat):

    arrayInd(83, .dim = dim(mat))
    
    #      [,1] [,2]
    # [1,]    3    9
    
    # check
    all.equal(
      mat[arrayInd(83, .dim = dim(mat))],
      mat[83]
    )
    # [1] TRUE
    

    Or for ease of reading, add useNames = TRUE:

    arrayInd(83, .dim = dim(mat),
             useNames = TRUE)
    
    #       row  col
    # [1,]    3    9
    

    For a little more detail, arrayInd is related to which (see ?arrayInd) except its explicitly used to convert linear indices into row/col positions. It will return a matrix.

    Note, you can use a vector of indices:

    inx <- c(83, 92)
    arrayInd(inx, dim(mat))
    
    #      [,1] [,2]
    # [1,]    3    9
    # [2,]    2   10
    

    And when using a vector of desired positions, if you wanted to clean it up for ease of identifying, could rename rows/cols like this:

    indx <- c(83, 92)
    `rownames<-`(arrayInd(indx, .dim = dim(mat), useNames = TRUE), paste0("ix", indx))
    
    #      row column
    # ix83   3      9
    # ix92   2     10