R fastest way to multiply rows of a matrix by rows

2019-06-25 07:00发布

问题:

I want to multiply rows of a matrix by EACH row (element) of a vector, not the entire vector (as the other question already posted talks about.)

for example, I want to use these two matrices (or oo is a vector, since it's one column)

oo=matrix(1:3,3,1)
oop=matrix(1:9,3,3,byrow=TRUE)

to output

1  2  3 
8  10 12
21 24 27

I need to do this VERY efficiently, as I need to do it with massive amounts of data thousands of times. I used

diag(as.vector(oo))%*%oop

but this is much too slow.

回答1:

R>oop*drop(oo)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    8   10   12
[3,]   21   24   27