Matrix Multiplication Error in R: Requires Numeric Matrix (2 Examples)
In this tutorial, I’ll illustrate how to deal with the error “requires numeric/complex matrix/vector arguments” in the R programming language.
Example Data
data(iris) # Load iris data set iris_num <- iris[ , 1:4] # Numeric columns head(iris_num) # Head of iris_num # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 5.1 3.5 1.4 0.2 # 2 4.9 3.0 1.4 0.2 # 3 4.7 3.2 1.3 0.2 # 4 4.6 3.1 1.5 0.2 # 5 5.0 3.6 1.4 0.2 # 6 5.4 3.9 1.7 0.4 |
data(iris) # Load iris data set iris_num <- iris[ , 1:4] # Numeric columns head(iris_num) # Head of iris_num # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 5.1 3.5 1.4 0.2 # 2 4.9 3.0 1.4 0.2 # 3 4.7 3.2 1.3 0.2 # 4 4.6 3.1 1.5 0.2 # 5 5.0 3.6 1.4 0.2 # 6 5.4 3.9 1.7 0.4
Example 1: Replicating the Error Message – requires numeric/complex matrix/vector arguments
t(iris_num) %*% iris_num # Matrix multiplication with data frame does not work # Error in t(iris_num) %*% iris_num : # requires numeric/complex matrix/vector arguments |
t(iris_num) %*% iris_num # Matrix multiplication with data frame does not work # Error in t(iris_num) %*% iris_num : # requires numeric/complex matrix/vector arguments
Example 2: Solving the Error Message – requires numeric/complex matrix/vector arguments
t(iris_num) %*% as.matrix(iris_num)# Matrix multiplication with matrix works fine # Sepal.Length Sepal.Width Petal.Length Petal.Width # Sepal.Length 5223.85 2673.43 3483.76 1128.14 # Sepal.Width 2673.43 1430.40 1674.30 531.89 # Petal.Length 3483.76 1674.30 2582.71 869.11 # Petal.Width 1128.14 531.89 869.11 302.33 |
t(iris_num) %*% as.matrix(iris_num)# Matrix multiplication with matrix works fine # Sepal.Length Sepal.Width Petal.Length Petal.Width # Sepal.Length 5223.85 2673.43 3483.76 1128.14 # Sepal.Width 2673.43 1430.40 1674.30 531.89 # Petal.Length 3483.76 1674.30 2582.71 869.11 # Petal.Width 1128.14 531.89 869.11 302.33
Related Tutorials & Further Resources
Please find some related R tutorials on topics such as coding errors and numeric values below.