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:
我有一个矩阵10x4,我有一个有10个元素的向量。每个元素都是应该检索的矩阵的列索引。这是一个例子:
> 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
It means that I want to get the 3rd column from row 1,4th column from row 2, 1st column from row 3, ...
这意味着我想从第2行第1,4列第3列第3列获取第3列,...
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?
我试图创建一个包含两列的data.frame,一个是来自1; 10的row.indx,另一列是Idx,但它不起作用。有什么建议我如何访问指定的元素?
1 个解决方案
#1
10
This should do it for you:
这应该为你做:
M.mat[cbind(seq_along(Idx),Idx)]
#1
10
This should do it for you:
这应该为你做:
M.mat[cbind(seq_along(Idx),Idx)]