How to Solve R Error: Multiplication requires numeric/complex matrix/vector arguments

by | Programming, R, Tips

This error occurs when you try to perform matrix multiplication with a data frame instead of a matrix. The %*% operator cannot handle data frames. You can solve the error by converting the data frame to a matrix using the as.matrix() function. For example,

data <- data.frame(x = 1:4,
                   y = c(4, 9, 1, 10),
                   z = sample(200, 4))

mat <- as.matrix(data)

This tutorial will go through the error in detail with code examples.


Table of contents

Example

Let’s look at an example to reproduce the error. First, we will define a data frame.

# Create data frame

data <- data.frame(x = 1:4,
                   y = c(4, 9, 1, 10),
                   z = sample(200, 4))
  x  y   z
1 1  4  73
2 2  9 172
3 3  1 107
4 4 10 114

Next, we will try to multiply the data frame by its transpose using the matrix multiplication operator %*%.

# Get transpose of data frame using t() and attempt multiply by original data frame

data_by_transpose <- t(data) %*% data

Let’s run the code to see what happens:

Error in t(data) %*% data : 
  requires numeric/complex matrix/vector arguments

The error occurs because we are attempting to do matrix multiplication, but the %*% handles matrix objects, not data frames.

Solution

We can solve the error by converting the data frame to a matrix using the as.matrix() function.

mat <- as.matrix(data)
mat
     x  y   z
[1,] 1  4  73
[2,] 2  9 172
[3,] 3  1 107
[4,] 4 10 114

Once we have the matrix, we can perform the matrix multiplication operation.

data_by_transpose <- t(mat) %*% mat

Let’s run the code to get the resultant matrix.

     x    y     z
x   30   65  1194
y   65  198  3087
z 1194 3087 59358

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R-related errors, go to the articles: 

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!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

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.

Buy Me a Coffee