Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to index and multiply two matrices efficiently?

Tags:

indexing

r

matrix

I have two matrices "A", "B", and a data frame "C". They are

A <- matrix(1:10, nrow = 2) 
colnames(A) <- letters[1:5]

B <- matrix(11:16, nrow = 2)
colnames(B) <- letters[6:8]

C <- data.frame(ix1 = c("a", "d"), ix2 = c("f", "h"))

I want to create a vector "vec" with length 2 and values

vec[1] = A[,"a"] %*% B[,"f"]
vec[2] = A[,"d"] %*% B[,"h"]

This can be done easily with a for loop, but it is time consuming when the sizes of "A", "B" and "C" grow. How to do it efficiently?

like image 376
llcc Avatar asked Mar 16 '23 09:03

llcc


1 Answers

You can vectorize as follows, but I'm not sure how costly it would be to transpose A

(vec <- diag(crossprod(A[, as.character(C$ix1)], B[, as.character(C$ix2)])))
## [1]  35 233
like image 69
David Arenburg Avatar answered Mar 24 '23 00:03

David Arenburg