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.
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
using apply
> t(apply(mat,1 , function(x) x*vec))
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 1 2 3 4
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With