Get the vector of values from different columns of a matrix

妖精的绣舞 提交于 2019-11-27 03:28:32

问题


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

It means that I want to get the 3rd column from row 1,4th column from row 2, 1st column from row 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?


回答1:


This should do it for you:

M.mat[cbind(seq_along(Idx),Idx)]


来源:https://stackoverflow.com/questions/20036255/get-the-vector-of-values-from-different-columns-of-a-matrix

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