Skip to main content
HomeTutorialsR Programming

How to Fix the Non-Numeric Argument to Binary Operator Error in R

The non-numeric argument to binary operator error in R happens when you try to do arithmetic on non-numeric data, like a character string or factor.
Jun 2024  · 8 min read

You might have encountered this error when programming in R: Error: non-numeric argument to binary operator. This can occur when performing a mathematical operation on data containing non-numeric values, such as strings or characters.

In this tutorial, I'll guide you through how to tackle and fix this error. I will first provide a short answer and then I will dive deeper so you can understand better why this error occurs.

The Short Answer: How to Fix the Non-Numeric Argument to Binary Operator Error in R

For those in a hurry, fixing the non-numeric argument to binary operator error in R involves converting data to numeric types before performing arithmetic operations. This method ensures that all elements in your data are suitable for mathematical calculations.

In the following example, the as.numeric() function directly converts the characters vector to numeric, ensuring that the addition operation is performed without error.

characters <- c("5", "10", "15")

characters <- as.numeric(characters)

result <- characters + 10

print(result)

Why the Error Occurs

In R, arithmetic operations are designed to work with numeric data types. When you encounter the non-numeric argument to binary operator error, it typically indicates a misuse of arithmetic operators with non-numeric data types, such as strings or factors. For more on R data types, read our Data Types in R tutorial.

This can occur in several common scenarios:

  • Operations on Character Strings: The error can occur when trying to perform arithmetic on text data.
  • Operations on Factor Data Types: The error occurs when R converts strings to factors within data frames, especially when importing data, leading to unintended non-numeric types.
  • Operations on Lists or Other Complex Structures: The error also occurs when using arithmetic operators on lists or similar structures unsuitable for such operations.

How to Reproduce and Fix the Error

Let's create a simple dataset and perform operations that will intentionally trigger this error to illustrate how it can occur. We will then fix the error in each case.

How to reproduce and fix the error for character strings

In our first example, we see this error message because the elements of the characters vector are not of a numeric type but are instead character strings.

characters <- c("5", "10", "15")

result <- characters + 10

print(result)

To fix this, we convert to numeric using as.numeric():

characters <- c("5", "10", "15")

characters <- as.numeric(characters)

result <- characters + 10

print(result)

How to reproduce and fix the error for factors

In our next example, we will reproduce the error for factors.

factors <- factor(c("5", "10", "15"))

result <- factors + 10

print(result)

To fix this, we convert to numeric by first converting to character. We do this because, in R, factors are stored as integer vectors with a corresponding set of character levels.

When you convert a factor directly to numeric using as.numeric(), R returns the underlying integer codes, which is the internal integer representation of the factor levels, instead of the actual character values. Converting the factor to a character first retrieves the actual levels as character strings, which can then be correctly converted to numeric values.

factors <- factor(c("5", "10", "15"))

factors <- as.numeric(as.character(factors))

result <- factors + 10

print(result)

How to reproduce and fix the error for lists

In our next example, we will reproduce the error for lists. 

list_data <- list("5", "10", "15")

result <- list_data + 10

print(result)

To fix this, we extract and convert elements to numeric. The unlist() function converts the list into a vector. 

list_data <- list("5", "10", "15")

list_data <- as.numeric(unlist(list_data))

result <- list_data + 10

print(result)

How to reproduce and fix the error for mixed data types

This next example is a bit more complicated. None of our previous techniques would work in this case because we would encounter "20a" that cannot be converted to a numeric value. 

The sapply() function offers a good fix in this case. It applies a specified function to each element of our vector. In our case, we define a function that attempts to convert each element to a numeric value.

mixed_data <- list("5", 10, "15", "20a")

numeric_data <- sapply(mixed_data, function(x) {
  if (is.numeric(x)) {
    return(x)
  } else if (!is.na(as.numeric(x))) {
    return(as.numeric(x))
  } else {
    return(NA)
  }
})

result <- numeric_data + 10

print(result)

For more information on functional programming in R, check out our Intermediate Functional Programming with purrr course. For more on the apply() family of functions, read our Tutorial on the R Apply Family

Additional Things to Know

Debugging with traceback

When an error occurs, traceback() can be a valuable tool for debugging. It provides a sequence of calls that led to the error, helping you identify the exact point of failure.

traceback()

After running this command, R will print the sequence of function calls that led to the error. This can provide insights into where the non-numeric data might have been introduced.

Review data input methods

You may also want to double-check how data is imported and ensure it is converted correctly. When importing data, especially from CSV files, R may automatically convert character data to factors. It's important to control this behavior to ensure your data is imported correctly.

# Assuming data is read from a CSV incorrectly imported as factors
data <- read.csv("data.csv", stringsAsFactors = TRUE)

data$column <- as.numeric(as.character(data$column))

In this example, data is imported from a CSV file with stringsAsFactors set to TRUE. We then convert the factor column to a character and subsequently to numeric to ensure proper data type for arithmetic operations.

How to Prevent the Error

Using conditional checks

To help prevent this error from occurring, try to implement conditional checks to ensure that data types are suitable for operations. Checking the data type and handling any necessary conversions conditionally is good practice before performing operations.

In the following example, we check if the data is numeric. If not, we convert it to numeric before proceeding with the arithmetic operation. This catches any wrong data types and converts them accordingly to numeric. 

data <- "20"

if(is.numeric(data)) {
  result <- data + 10
} else {
  data <- as.numeric(data)
  result <- data + 10
}

print(result)

conditional checks example

Conclusion and Additional Resources

I hope this article has been helpful in solving your problem. Errors such as the non-numeric argument to binary operator error are common in programming, and knowing how to handle them is important. Understanding data types and proper conversions can help prevent this error from occurring.

To help you with R, you can check our R cheat sheets or our free Introduction to R course or, for a deeper understanding, try our R Programming Skill Track.


Photo of Austin Chia
Author
Austin Chia

I'm Austin, a blogger and tech writer with years of experience both as a data scientist and a data analyst in healthcare. Starting my tech journey with a background in biology, I now help others make the same transition through my tech blog. My passion for technology has led me to my writing contributions to dozens of SaaS companies, inspiring others and sharing my experiences.

Frequently Asked Questions

What is a non-numeric argument?

A non-numeric argument is a value or variable that cannot be interpreted as a number in a programming language like R.

How can I spot this error in my code?

The error message usually includes the phrase "non-numeric argument", making it easy to identify.

Does this error only occur in R?

No, this error can occur in other programming languages as well. However, the error message might appear differently.

Is there a way to avoid this error altogether?

Yes, by ensuring that all values and variables in your code are compatible with the specific operator being used.

Can I use any type of operator with non-numeric arguments?

No, some operators may only be used with numerical values and will result in this error if given non-numeric arguments.

Topics

Learn R with DataCamp

course

Introduction to R

4 hours
2.7M
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

cheat sheet

Text Data In R Cheat Sheet

Welcome to our cheat sheet for working with text data in R! This resource is designed for R users who need a quick reference guide for common tasks related to cleaning, processing, and analyzing text data.
Richie Cotton's photo

Richie Cotton

5 min

tutorial

Operators in R

Learn how to use arithmetic and logical operators in R. These binary operators work on vectors, matrices, and scalars.
DataCamp Team's photo

DataCamp Team

4 min

tutorial

Basic Programming Skills in R

Practice basic programming skills in R by using course material from DataCamp's free Model a Quantitative Trading Strategy in R course.
Ryan Sheehy's photo

Ryan Sheehy

5 min

tutorial

Data Types in R

Learn about data types and their importance in a programming language. More specifically, learn how to use various data types like vector, matrices, lists, and dataframes in the R programming language.
Aditya Sharma's photo

Aditya Sharma

12 min

tutorial

Conditionals and Control Flow in R Tutorial

Learn about relational operators for comparing R objects and logical operators for combining boolean TRUE and FALSE values. You'll also construct conditional statements.
Aditya Sharma's photo

Aditya Sharma

13 min

tutorial

Sorting Data in R

How to sort a data frame in R.
DataCamp Team's photo

DataCamp Team

2 min

See MoreSee More