KH Kim
KH Kim

Reputation: 1175

Another way to access matrix elements in R

mat <- matrix(c(1,2,3,4,5,6,7,8,9), ncol=3)

mat[1:2, 1:2] 

returns new matrix(c(1,2,4,5), ncol=2).

is there anyway to access the matrix elements like plot's x, y position?

some function(mat, 1:2, 1:2) returns c(1,5) because mat[1,1] and mat[2,2] are 1,5.

some function(mat, c(1,1,2), c(2,1,1) returns

c(4, 1, 2)

because mat[1,2], mat[1,1], mat[2,1] are 4,1,2.

Upvotes: 3

Views: 1553

Answers (3)

KH Kim
KH Kim

Reputation: 1175

I came up with another looking-ugly answer myself.

mapply(function(x,y){'['(mat,x,y)} , c(1,2), c(2,3) )

I compared "mat[cbind" and "mapply(function(x,y){'['(mat,x,y)} ,",

and the first one was about 100 times faster! ;-p

using the function xy2elem is as fast as using cbind! Impressive!

Upvotes: 0

James
James

Reputation: 66844

You can convert from matrix "co-ordinates" to element numbers and subset using those:

xy2elem <- function(m,x,y) x + nrow(m)*(y-1)

mat[xy2elem(mat,1:2,1:2)]
[1] 1 5
> mat[xy2elem(mat,c(1,1,2),c(2,1,1))]
[1] 4 1 2

Upvotes: 2

David Robinson
David Robinson

Reputation: 78610

You can access it this way using cbind:

mat[cbind(1:2, 1:2)]
# [1] 1 5
mat[cbind(c(1, 1, 2), c(2, 1, 1))]
# [1] 4 1 2

Upvotes: 6

Related Questions