views:

416

answers:

1

Is there a function to get an index (row number and column number) for a matrix?

Suppose that I have a simple matrix:

a <- matrix(1:50, nrow=5)

Is there an easy way to get back something like c(3, 5) for the number "23", for instance? In this case, saying which(a==23) just returns 23.

This seems to work but I'm sure that there's a better way:

matrix.index <- function(a, value) {
  idx <- which(data.frame(a)==value)
  col.num <- ceiling(idx/nrow(a))
  row.num <- idx - (col.num-1) * nrow(a)
  return(c(row.num, col.num))
}
> matrix.index(a, 23)
[1] 3 5
> matrix.index(a, 50)
[1]  5 10
+4  A: 

Just looked at the help for which() after posting this and found the answer: the arr.ind parameter.

which(a==23, arr.ind=TRUE)
     row col
[1,]   3   5
Shane