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

r

Solution

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

Problem

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.

Original source

Related problems