I have a Matrix A which looks like
A = matrix(1:9,3,3)
A
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
and a matrix of indices of elements I am interested in. Column 1 contains row indices, and column 2 contains column indices:
v = matrix(c(1, 3, 2, 2, 2, 3), nrow = 3, ncol = 2)
v
[,1] [,2]
[1,] 1 2
[2,] 3 2
[3,] 2 3
I want to use the rows and column indices in 'v' to extract numbers from 'A'; the indices correspond to the numbers 4 (A[1, 2]
), 6 (A[3, 2]
) and 8.
How can I extract those numbers directly from 'A' without using a loop?
When I use
A[v[ , 1], v[ , 2]]
I get
[,1] [,2] [,3]
[1,] 4 4 7
[2,] 6 6 9
[3,] 5 5 8
because R takes all combinations of the first and second column of 'v'.
What I want is an expression which gives me directly 4, 6, 8.
I could just take the diagonal elements but there must be an easier way.
A[v]
– A5C1D2H2I1M1N2O1R2T1