Search code examples
rdataframeperformancematrix

how to do efficiently element wise multiplication of two matrices in r


I want to do elementwise multiplication of two large matrices, i want to do it the most efficiently possible.

Currently i am using the base operator *

For example if i have a DF1 like the next:

A B
1 2
3 4

and a DF2 like the next:

X Y
5 6
7 8

DF1*DF2 results in

X Y
5 12
21 32

how can i make it faster?


Solution

  • Below are several possible options, and you can choose the one you like.

    For speed, you can try the method in f3()

    set.seed(0)
    A <- as.data.frame(matrix(runif(100), 10, 10))
    B <- as.data.frame(matrix(runif(100), 10, 10))
    
    f1 <- function() A * B
    f2 <- function() as.data.frame(as.matrix(A) * as.matrix(B))
    f3 <- function() as.data.frame(`dim<-`(unlist(A, FALSE, FALSE) * unlist(B, FALSE, FALSE), dim(A)))
    f4 <- function() list2DF(Map(`*`, A, B))
    
    microbenchmark(
        f1(),
        f2(),
        f3(),
        f4(),
        check = "equal",
        unit = "relative"
    )
    

    and you will see

    Unit: relative
     expr       min        lq     mean    median        uq       max neval
     f1() 19.315789 18.795854 9.927453 16.090020 14.320574 1.0078119   100
     f2()  5.318182  5.192839 3.243506  4.736301  4.274322 0.7957232   100
     f3()  1.000000  1.000000 1.000000  1.000000  1.000000 1.0000000   100
     f4()  3.533493  3.342965 2.057707  2.988258  2.640750 0.6603172   100