How to subset a matrix with different column positions for each row? [duplicate]
I want to subset a matrix using different (but one) column for every row. So propably apply could do the job? But propably also smart subsetting could work, but i havent found a solution. Computation time is an issue - I have a solution with a for loop, but loading the matrix in the RAM several times is just too slow. Here is an example:
Matrix M and vector v are given,
M<-matrix(1:15,nrow=5,ncol=3)
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
v<-c(3,1,1,2,1)
and the solution shall be:
(11,2,3,9,5)
Solution 1:
We can try the row/column indexing
M[cbind(1:nrow(M), v)]
#[1] 11 2 3 9 5
Solution 2:
Just for fun, here's an another solution using a vector indexing
t(M)[v + (seq_len(nrow(M)) - 1) * ncol(M)]
# [1] 11 2 3 9 5