I am currently learning about matrix operations in R, and I encountered an output that I did not anticipate when multiplying a vector with a matrix. My understanding was that multiplication would be conducted element-wise, but the output suggests otherwise. The code I ran is as follows:
num_matrix <- matrix(1:9, byrow = TRUE, nrow = 3)
new_matrix <- c(1,2,3) * num_matrix
print(new_matrix)
The output I got is:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 8 10 12
[3,] 21 24 27
This looks like the vector c(1,2,3) has been multiplied with each column of num_matrix, which contradicts my initial expectation of a row-wise operation. Could someone explain why the multiplication behaves like this and not row-wise as I expected?
Additionally, if I want to multiply a vector with each row of a matrix, rather than with each column, how can I achieve that in R?
Thank you for any assistance!
Matrices in R are vectors in column-major order. You can transpose your matrix to have elements recycled along columns that were previously rows, and then transpose back:
For kicks, here's a few other methods and their benchmarks. Note that treating this as a matrix multiplication will be fastest when the input is small, but doesn't scale well -- transposing is more consistent.
Edit: the method of @ThomasIsCoding (
f5below) turns out to be faster throughout!