Say I have two matrices:
> a
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 6 10 5 7 2 2 6
[2,] 10 6 7 7 4 3 12
[3,] 11 10 2 10 6 11 9
and
> b
[,1] [,2] [,3]
[1,] 4 1 4
[2,] 3 6 3
[3,] 2 5 2
The number of rows in a
and b
is identical. I am looking for a vectorized way to extract items from a
indicated by the column numbers in b
, on a row-by-row basis. The result c
should therefore look as follows:
> c
[,1] [,2] [,3]
[1,] 7 6 7
[2,] 7 3 7
[3,] 10 6 10
a[,b[1,]]
or a[,b[2,]]
or a[,b[3,]]
manage to get the correct results for rows 1, 2 and 3 respectively only. Can this be done with a simple matrix function at all? Is apply
necessary?
I have tried to adapt a solution to a similar problem in Index values from a matrix using row, col indicies but didn't understand how cbind was used here to extract matrix elements.