如何对每行具有不同列位置的矩阵进行子集化? [英] How to subset a matrix with different column positions for each row?
本文介绍了如何对每行具有不同列位置的矩阵进行子集化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对每一行使用不同(但只有一个)列的矩阵进行子集化.那么适当地申请可以完成这项工作吗?但也许智能子集也可以工作,但我还没有找到解决方案.计算时间是一个问题 - 我有一个带有 for 循环的解决方案,但是在 RAM 中多次加载矩阵太慢了.下面是一个例子:
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:
矩阵M和向量v给定,
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)
解决方案是:
(11,2,3,9,5)
推荐答案
我们可以试试行/列索引
We can try the row/column indexing
M[cbind(1:nrow(M), v)]
#[1] 11 2 3 9 5
这篇关于如何对每行具有不同列位置的矩阵进行子集化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文