Multiply rows of matrix by vector?

I think you’re looking for sweep().

# Create example data and vector
mat <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3

vec <- 1:5

# Use sweep to apply the vector with the multiply (`*`) function
#  across columns (See ?apply for an explanation of MARGIN) 
sweep(mat, MARGIN=2, vec, `*`)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    4    6    8   10
[3,]    3    6    9   12   15

It’s been one of R’s core functions, though improvements have been made on it over the years.

Leave a Comment