11

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
Humble Debugger
  • 4,439
  • 11
  • 39
  • 56
  • 2
    It seems like you are coming from C++ background and thus the "loop" way of thinking. R is a vectorized language and you usually can avoid loops unlseed each entry supplies diffirent conditions. There is a workaround though for C++ users in the Rcpp package. Take a look [here](http://quant.stackexchange.com/questions/728/switching-from-c-to-r-limitations-applications) – David Arenburg May 14 '14 at 10:16
  • @DavidArenburg you are right :). However I tried * and %*%. Operator * worked when a_ has one column. – Humble Debugger May 14 '14 at 10:34
  • 2
    `*` and `%*%` are different things. The first is just multiplyinh each element of first vector to its corresponding element in the second, while latter is a matrix multiplication – David Arenburg May 14 '14 at 10:41

1 Answers1

15

Yes, normal multiplication with b_ as a vector:

a_*as.vector(b_)
     [,1] [,2]
[1,]    2    8
[2,]   -2   -3
[3,]    3    2
James
  • 65,548
  • 14
  • 155
  • 193