Open In App

How to Fix: non-numeric argument to binary operator in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see How to Fix: non-numeric argument to the binary operator in R Programming Language.

The “non-numeric argument to binary operator” error occurs when we perform arithmetic operations on non-numeric elements.

How to produce this error

Here we can see, we have to take the string element and try to add it with a numeric element, so it will occur.

R




num <- "2"
res <- num + 4
print(res)


Output:

Error in num + 4: non-numeric argument to binary operator

How to solve it?

To solve this error we will convert non-numeric data into numeric data using as.numeric() methods.

Example 1: Perform into vector

We will convert non-numeric data from vector into numeric data using as.numeric() methods.

R




num <- "2"
res <- as.numeric(num) + 3
print(res)


Output:

5

Example 2: Perform into Dataframe

Here we will create 3 columns and try to add numeric columns to non-numeric columns using as.numeric() methods.

R




# Create data for chart
df <-data.frame("Course"=c('DSA','C++','R','Python'),
                  "Practial_Marks"=c(7,5,8,6),
                  "Sub_Marks" = c('4', '4','3','4'))
  
# attempt to create new column called 'net'
df$Add_on <- df$Practial_Marks + as.numeric(df$Sub_Marks)
print(df)


Output:

 Course Practial_Marks Sub_Marks Add_on
1    DSA              7         4      9
2    C++              5         4      7
3      R              8         3      9
4 Python              6         4      8


Last Updated : 21 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads