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]].
v
i
m[i,y[i]]
I thought I would m[,y]do it, but this is clearly wrong.
m[,y]
You can use cbind()to create a matrix that will be used for indexing.
cbind()
m[cbind(seq_along(y), y)] # [1] 1 7 8 4 5
In addition, since in this particular case we select rows 1, 2, ..., nrow(m),
1, 2, ..., nrow(m)
diag(m[, y]) # [1] 1 7 8 4 5