This is a really basic question, but I can't seem to solve it or find an answer for it anywhere : suppose I have two vectors x,y
of coordinates and a matrix m
.
I would like a vector z
such that z[i] = m[x[i],y[i]]
for all i
.
I tried z=m[x,y]
, but that creates a memory overflow. The vector and matrix are quite large so looping is pretty much out of the question. Any ideas ?
Use cbind
. Here's a simple example:
mat <- matrix(1:25, ncol = 5)
mat
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 6 11 16 21
# [2,] 2 7 12 17 22
# [3,] 3 8 13 18 23
# [4,] 4 9 14 19 24
# [5,] 5 10 15 20 25
x <- 1:5
y <- c(2, 3, 1, 4, 3)
mat[cbind(x, y)]
# [1] 6 12 3 19 15
## Verify with a few values...
mat[1, 2]
# [1] 6
mat[2, 3]
# [1] 12
mat[3, 1]
# [1] 3
From ?Extract
:
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 anNA
produce anNA
in the result.
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