Matrix Indexing by Vector

m = matrix(1:10, nrow = 5, ncol = 2)
y = c(1,2,2,1,1)

I need a vector vwhose element is ith m[i,y[i]].

I thought I would m[,y]do it, but this is clearly wrong.

+4
source share
2 answers

You can use cbind()to create a matrix that will be used for indexing.

m[cbind(seq_along(y), y)]
# [1] 1 7 8 4 5
+6
source

In addition, since in this particular case we select rows 1, 2, ..., nrow(m),

diag(m[, y])
# [1] 1 7 8 4 5
+4
source

All Articles