Subset a matrix according to a columns vector

I have a matrix, H. I want to select a value from each row, choosing the column from vector P.

H = matrix(data=runif(6),ncol=2)
P = c(2,1,2)

The output I am after is a vector containing

c(H[1,P[1]],H[2,P[2]],H[3,P[3]])

I'm working with larger data, so a generic way of doing this would be good.

This works diag(H[,P]), but: a) I don't understand why H[,P] returns a square matrix, and b) I would rather not use an extra function (in this case diag).

My apologies if this has been asked before.


Solution 1:

Try

H[cbind(seq_len(nrow(H)), P)]
## [1] 0.6733731 0.7396847 0.5953580

Here we are indexing by consecutive rows and columns indicated in P


Regarding your question, so the reason H[, P] returns a matrix is because you are telling R:

select all rows in columns: 2, 1, 2 from matrix "H"

thus the result that you are getting is a matrix with identical first and third columns.