m = matrix(1:10, nrow = 5, ncol = 2)
y = c(1,2,2,1,1)
I want a vector v whose ith element is m[i,y[i]].
I thought m[,y] would do it, but that's clearly wrong.
You can use cbind() to create a matrix to be used for indexing.
m[cbind(seq_along(y), y)]
# [1] 1 7 8 4 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With