Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use values from 2 matrices to index a third in R

Tags:

r

matrix

apply

I'm optimizing a more complex code, but got stuck with this problem.

a<-array(sample(c(1:10),100,replace=TRUE),c(10,10))  
m<-array(sample(c(1:10),100,replace=TRUE),c(10,10))  
f<-array(sample(c(1:10),100,replace=TRUE),c(10,10))  
g<-array(NA,c(10,10)) 

I need to use the values in a & m to index f and assign the value from f to g
i.e. g[1,1]<-f[a[1,1],m[1,1]] except for all the indexes, and as optimally/fast as possible

I could obviously make a for loop to do this for me but that seems rather dumb and slow. It seems like I should be able to us something in the apply family, but I've had no luck with figuring out how to do that. I do need to keep the data structured as it is here so that I can use matrix operations in different parts of my code. I've been searching for an answer to this but haven't found anything particularly helpful yet.

like image 804
arudolph.bio Avatar asked Dec 13 '25 23:12

arudolph.bio


1 Answers

g[] <- f[cbind(c(a), c(m))]

This takes advantage of the fact that matrices can be addressed as vectors and using a matrix as the index.

like image 168
Nick Kennedy Avatar answered Dec 15 '25 11:12

Nick Kennedy