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.
From ?"["
, you will find the following:
When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i.
and later on...
A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector. Negative indices are not allowed in the index matrix. NA and zero values are allowed: rows of an index matrix containing a zero are ignored, whereas rows containing an NA produce an NA in the result.
Thus, what you are looking for is simply:
A[v]
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