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!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!