How to effectively index and multiply two matrices?

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 vec vector with length 2 and values

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

This can easily be done with a loop for, but it takes a long time when the sizes "A", "B" and "C" increase. How to do it efficiently?

+4
source share
2 answers

You can use mapply:

vec = mapply(function(u,v) A[,u]%*%B[,v], c('a','d'), c('f','h'))

If you want to use data.frame C:

vec = mapply(function(u,v) A[,u]%*%B[,v], as.character(C[,1]), as.character(C[,2]))
#  a   d 
# 35 233

What really matters is the number of lines C, the number of lines in Aand Bmay not be a bottleneck:

v1=rnorm(1000000)
v2=rnorm(1000000)

#> system.time(v1%*%v2)
#   user  system elapsed 
#   0.01    0.00    0.02 
+3

, , , A

(vec <- diag(crossprod(A[, as.character(C$ix1)], B[, as.character(C$ix2)])))
## [1]  35 233
+4

All Articles