Index a matrix using two equal-length vectors for row and column indices

Viewed 84

Imagine you have a 5x5 matrix and want to select values using two equal-length vectors, one representing the index row and the other representing the index column:

m <- matrix(1:25, ncol = 5)
R <- c(1, 3, 5)
C <- c(2, 4, 4)

The desired output here is a single vector of of 6 (row 1, column 2), 18 (row 3, column 4), 20 (row 5, column 4).

The best I could come up with was:

diag(m[R,C])

But this constructs a matrix of size length(R) * length(C) and so is slow if R and C are long.

How do you do this?

3 Answers

You can use cbind(R, C) for indexing with [:

m[cbind(R,C)]

#> [1]  6 18 20

using mapply

mapply(function(r,c) {m[r,c]}, r = R, c = C)
# [1]  6 18 20

creating a matrix for indices.

m[matrix(c(R,C), ncol=2)]
# [1]  6 18 20

Another option is

M[do.call(cbind, list(R, C))]
Related