Search code examples
rmatrixindices

Create dataframe of all array indices in R


Using R, I'm trying to construct a dataframe of the row and col numbers of a given matrix. E.g., if

a   <- matrix(c(1:15), nrow=5, ncol=3)

then I'm looking to construct a dataframe that gives:

row col
  1   1
  1   2
  1   3
  .   .
  5   1
  5   2
  5   3

What I've tried:

row <- matrix(row(a), ncol=1, nrow=dim(a)[1]*dim(a)[2], byrow=T)
col <- matrix(col(a), ncol=1, nrow=dim(a)[1]*dim(a)[2], byrow=T)
out <- cbind(row, col)
colnames(out) <- c("row", "col")

results in:

    row col
[1,]   1   1
[2,]   2   1
[3,]   3   1
[4,]   4   1
[5,]   5   1
[6,]   1   2
[7,]   2   2
[8,]   3   2
[9,]   4   2
[10,]  5   2
[11,]  1   3
[12,]  2   3
[13,]  3   3
[14,]  4   3
[15,]  5   3

Which isn't what I'm looking for, as the sequence of rows and cols in suddenly reversed, even tough I specified "byrow=T". I don't see if and where I'm making a mistake but would hugely appreciate suggestions to overcome this problem. Thanks in advance!


Solution

  • I'd use expand.grid on the vectors 1:ncol and 1:nrow, then flip the columns with [,2:1] to get them in the order you want:

    > expand.grid(seq(ncol(a)),seq(nrow(a)))[,2:1]
       Var2 Var1
    1     1    1
    2     1    2
    3     1    3
    4     2    1
    5     2    2
    6     2    3
    7     3    1
    8     3    2
    9     3    3
    10    4    1
    11    4    2
    12    4    3
    13    5    1
    14    5    2
    15    5    3