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?
This should do it for you:
M.mat[cbind(seq_along(Idx),Idx)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With