How to Solve R Error: non-numeric argument to binary operator

by | Programming, R, Tips

If you try to perform an arithmetic operation and one or both of the operands are non-numeric, you will raise the error: non-numeric argument to binary operator. This error typically occurs when one of the operands is of character type.

To solve this error, you can convert a character to a number using the as.numeric() function.

Functions like diff() also perform arithmetic operations that require both values to be numeric.

This tutorial will go through the error in detail and how to solve it with code examples.


Binary Operations in R

A binary operation is a calculation that takes precisely two values (operands) to produce another value. Binary operators work on scalars, vectors, and matrices. Arithmetic operators are a subset of binary operators. Examples of arithmetic operators in R include:

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division
  • ^ or ** : exponentiation
  • %% : modulus
  • %/% : integer division

Arithmetic operators require both of the operands to be numeric.

Example: Adding two numbers together

Let’s look at a basic example of adding two numbers together:

5 + '3'
Error in 5 + "3" : non-numeric argument to binary operator

The error occurs because 3 is of type character. We can verify this using the class() function:

class(5)
class('3')
[1] "numeric"

[1] "character"

We can also check if a value is numeric using the built-in is.numeric() method:

is.numeric('3')
[1] FALSE

We can only perform arithmetic operations like addition with numeric values.

Solution

We can solve this error by using the built-in numeric() method to coerce the character object to type numeric. Let’s look at the revised code:

5 + as.numeric('3')

Let’s run the code to get the result:

[1] 8

We successfully added the two numbers together.

Example #2: Subtraction with two vectors

Consider an example of a data frame describing a team’s performance in terms of wins and losses over twelve months. The first column contains months, the second column contains the wins for each month, and the third contains the losses for each month.

df <- data.frame(month=c(1,2,3,4,5,6,7,8,9,10,11,12),
wins=c('10','7', '8', '12','5', '4','10', '8', '9', '7', '2', '11'),
losses=c(2, 5, 9, 1, 9, 10, 2, 4, 2, 3, 8, 3))

df
 month wins losses
1      1   10      2
2      2    7      5
3      3    8      9
4      4   12      1
5      5    5      9
6      6    4     10
7      7   10      2
8      8    8      4
9      9    9      2
10    10    7      3
11    11    2      8
12    12   11      3

Next, we will subtract the number of losses from the number of wins for each month to determine how often the team wins more than it loses per month.

df$net_wins <- df$wins - df$losses

Let’s run the code to see the result:

Error in df$wins - df$losses : non-numeric argument to binary operator

The error occurs because the wins vector is of type character. We can verify the type of the vector using class():

class(df$wins)
class(df$losses)
[1] "character"
[1] "numeric"

We can also verify if a column is numeric using is.numeric():

is.numeric(df$wins)
is.numeric(df$losses)
[1] FALSE
[1] TRUE

We can only perform arithmetic operations with vectors if both vectors are numeric.

Solution

We can use the numeric() method to coerce the df$wins vector to type numeric. Once the vector is of type numeric, we can perform the subtraction operation.

df$net_wins <- as.numeric(df$wins) - df$losses

df

Let’s run the code to see the result:

month wins losses net_wins
1      1   10      2        8
2      2    7      5        2
3      3    8      9       -1
4      4   12      1       11
5      5    5      9       -4
6      6    4     10       -6
7      7   10      2        8
8      8    8      4        4
9      9    9      2        7
10    10    7      3        4
11    11    2      8       -6
12    12   11      3        8

We successfully created a new column in the data frame for the net wins per month.

Example #3: non-numeric argument to binary operator using diff

Suppose we take the same data frame from the previous example and use diff() to observe how the number of wins changes from month to month:

diff(df$wins)

Let’s run the code to see the result:

Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] : 
  non-numeric argument to binary operator

The error occurs because the diff() function performs subtraction using the values in the df$wins vector. However, the df$wins vector is of type character.

Solution

We can solve this error by coercing the df$wins vector to numeric using the numeric() function. Let’s look at the revised code:

diff(as.numeric(df$wins))

Let’s run the code to get the result:

 [1] -3  1  4 -7 -1  6 -2  1 -2 -5  9

We successfully performed a diff on the wins vector to get the monthly changes in wins.

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