Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subset a matrix with different column positions for each row? [duplicate]

Tags:

r

matrix

subset

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)
like image 971
burbot Avatar asked Nov 05 '15 10:11

burbot


1 Answers

We can try the row/column indexing

M[cbind(1:nrow(M), v)]
#[1] 11  2  3  9  5
like image 138
akrun Avatar answered Oct 18 '22 04:10

akrun