从矩阵的不同列获取值的向量 [英] Get the vector of values from different columns of a matrix
本文介绍了从矩阵的不同列获取值的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个10x4的矩阵,我有一个包含10个元素的向量.每个元素都是应检索的该矩阵的列索引.这是示例:
I have a matrix 10x4, and I have a vector that has 10 elements. Each element is an column index of that matrix that should be retrieved. Here is the example:
> M.mat
[,1] [,2] [,3] [,4]
[1,] -0.4236174 0.2228897 0.11676857 0.16906735
[2,] -0.4860078 0.9862164 -2.04735716 -0.33708521
[3,] -0.6931023 -0.2255126 -0.58214338 -0.08705187
[4,] 0.4048169 0.8713917 0.38543781 -1.38207954
[5,] 2.4005044 1.2483514 0.66759229 -1.33667156
[6,] -1.2083913 0.2389032 0.29554618 -0.05910570
[7,] 0.8055317 -0.7978780 -0.31873361 0.57248675
[8,] -0.1606493 0.4110878 0.90236993 -0.62311446
[9,] 0.3721249 0.5276403 -0.09323399 -0.41223947
[10,] 2.0704414 0.1747543 0.45456052 -1.09215597
> Idx
[1] 3 4 1 2 1 3 1 1 2 3
这意味着我想从第2行的第1,4列获取第3列,从第3行的第1列获取...
It means that I want to get the 3rd column from row 1,4th column from row 2, 1st column from row 3, ...
我试图创建一个包含两列的data.frame,其中一列是1; 10中的row.indx,另一列是Idx,但是没有用.有什么建议可以访问指定的元素吗?
I tried to create a data.frame that contains two columns, one is row.indx from 1;10, and the other column is Idx, but it didn't work. Any suggestion how can I access the specified elements?
推荐答案
这应该为您做到:
M.mat[cbind(seq_along(Idx),Idx)]
这篇关于从矩阵的不同列获取值的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文