Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice way to multiply each row of a matrix by a vector in r [duplicate]

Tags:

r

I know this is a really basic question, sorry.

I want to multiply each row of a matrix by a vector. So I have:

mat=matrix(1,2,4)
vec=c(1,2,3,4)

#works but ugly:
new.mat=mat
for(i in 1:nrow(mat)){
  new.mat[i,]=mat[i,]*vec
}

I thought I'd found the answer with 'apply' but I couldn't get it to work the same way.

like image 282
Jessica B Avatar asked Jul 18 '13 15:07

Jessica B


3 Answers

I think this is what you are looking for...

t( t(mat) * vec )
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    3    4

* like most other operators in R is vectorised. The t is necessary because R will recycle column-wise. The apply solution is:

t( apply( mat , 1 , `*` , vec ) )
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    3    4
like image 143
Simon O'Hanlon Avatar answered Nov 05 '22 16:11

Simon O'Hanlon


using apply

> t(apply(mat,1 , function(x) x*vec))
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    1    2    3    4
like image 22
Jilber Urbina Avatar answered Nov 05 '22 17:11

Jilber Urbina


I'd have to say the most elegant way to go about this is:

mat=matrix(1,2,4)
vec=1:4
new.mat=t(vec*t(mat))
like image 40
nwknoblauch Avatar answered Nov 05 '22 18:11

nwknoblauch