element wise multiplication in r

23,916

Yes, normal multiplication with b_ as a vector:

a_*as.vector(b_)
     [,1] [,2]
[1,]    2    8
[2,]   -2   -3
[3,]    3    2
Share:
23,916
Humble Debugger
Author by

Humble Debugger

Algorithmic Trader / C/C++ Software Engineer

Updated on July 21, 2022

Comments

  • Humble Debugger
    Humble Debugger almost 2 years

    Is there an inbuilt function or operator to do the following in R :

    ElementwiseMultiply <- function ( a_, b_ )
    {
    c_ = a_ ;
    for ( i in 1:ncol(a_) )
    {
        c_[,i] = ( a_[,i] * b_ ) ;
    }
    return ( c_ );
    }
    

    For instance

    > a_
         [,1] [,2]
    [1,]    1    4
    [2,]    2    3
    [3,]    3    2
    > b_
         [,1]
    [1,]    2
    [2,]   -1
    [3,]    1
    > ElementwiseMultiply ( a_, b_ )
         [,1] [,2]
    [1,]    2    8
    [2,]   -2   -3
    [3,]    3    2