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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With