In order to perform matrix multiplication in R, the number of columns in the left matrix must be the same as the number of rows in the right matrix. This error occurs when you try to multiply two matrices where the number of columns in the left matrix does not match the number of rows in the right matrix.
You can get the dimensions of matrices using the dim()
function to ensure the matrices have appropriate dimensions for multiplication.
This tutorial will go through the error in detail with code examples.
Example
Let’s look at an example of trying to multiply two matrices in R. First, we will define the first matrix.
mat1 <- matrix(1:15, nrow=5) mat1
[,1] [,2] [,3] [1,] 1 6 11 [2,] 2 7 12 [3,] 3 8 13 [4,] 4 9 14 [5,] 5 10 15
Next, we will define the second matrix.
mat2 <- matrix(1:10, nrow=2) mat2
[,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10
Next, we will attempt to multiply the first matrix by the second matrix.
mat1 %*% mat2
Let’s run the code to see what happens:
Error in mat1 %*% mat2 : non-conformable arguments
The error occurs because the number of columns in the left matrix does not match the number of rows in the right matrix.
Solution
We can solve the error by first checking the dimensions of the matrices that we want to multiply using the dim() function.
dim(mat1)
[1] 5 3
dim(mat2)
[1] 2 5
From the output from the dim()
function, we can see:
- The first matrix has 5 rows and 3 columns
- The second matrix has 2 rows and 5 columns
Therefore, we need to have the second matrix on the left and the first matrix on the right during the multiplication operation. Let’s look at the revised code:
mat2 %*% mat1
Let’s run the code to see the result:
[,1] [,2] [,3] [1,] 95 220 345 [2,] 110 260 410
We successfully multiplied the two matrices.
Summary
Congratulations on reading to the end of this tutorial!
For further reading on R-related errors, go to the articles:
- How to Count the Number of NA in R
- How to Solve R Error in stripchart.default(x1, …) : invalid plotting method
- How to Solve R Error: `data` must be a data frame, or other object coercible by `fortify()`, not a numeric vector
Go to the online courses page on R to learn more about coding in R for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.