[R] multiplying a matrix by a vector
sarah.goslee at gmail.com
Thu Nov 3 22:33:08 CET 2016
> sweep(x, 2, y, "*")
[1,] 2 12
[2,] 4 15
[3,] 6 18
On Thu, Nov 3, 2016 at 5:05 PM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote:
> I have a matrix x and a vector y:
> x <- matrix(1:6, ncol = 2)
> y <- c(2,3)
> I need to multiply the first column of x by 2 (y) and the second
> column of x by 3 (y).
> Of course, I could do this - but it's column by column:
> x[,1] <- x[,1] * y
> x[,2] <- x[,2] * y
> Or I could repeat each element of y and multiply two matrices - that's better:
> y <- rep.row(y, nrow(x))
> x * y
> However, maybe there is a more elegant r-like way of doing it?
> Thank you!
> Dimitri Liakhovitski
More information about the R-help