Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting elements of a matrix with vectors of coordinates

Tags:

r

vector

matrix

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 ?

like image 803
Ulysse Mizrahi Avatar asked Dec 16 '13 17:12

Ulysse Mizrahi


1 Answers

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 an NA produce an NA in the result.

like image 121
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 18 '22 16:10

A5C1D2H2I1M1N2O1R2T1