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

佐手、 提交于 2019-11-27 07:50:29

问题


This question already has an answer here:

  • Subset a matrix according to a columns vector 2 answers

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)

回答1:


We can try the row/column indexing

M[cbind(1:nrow(M), v)]
#[1] 11  2  3  9  5



回答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


来源:https://stackoverflow.com/questions/33542325/how-to-subset-a-matrix-with-different-column-positions-for-each-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!