问题
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 ?
回答1:
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.
回答2:
Another way is to use the fact that you can index a matrix as if it were a vector, with elements numbered in column-major form. Using the example from @AnandoMahto:
mat[x+nrow(mat)*(y-1)]
[1] 6 12 3 19 15
来源:https://stackoverflow.com/questions/20617371/getting-elements-of-a-matrix-with-vectors-of-coordinates