Coding Ref

The R error, "non-numeric argument to binary operator" occurs when you try to perform a binary, or arithmetic, operation (+, −, ×, ÷) on two vectors, and one of the vectors is non-numeric, or on variables that are non-numeric. Use `as.numeric()`

to convert numbers formatted as a character into a number.

Binary operations:

- Addition (+)
- Subtraction (-)
- Multiplication (× or *)
- Division (÷ or /)

The error occurs when one of the vectors is a `character`

vector.

Here is an example of how the error occurs.

```
# ⛔️ Error: non-numeric argument to binary operator
1 + "one"
# ✅ this runs
1 + 1
```

To solve this, check if you are adding, subtracting, multiplying or dividing by a something that is not a number — it is usually a character. Change the character into a number and rerun your code.

`as.numeric()`

If your number is formatted as a character, you can manually change it to a number: `"one"`

to `1`

or use the function `as.numeric()`

.

```
char <- "5"
number <- as.numeric(char) + 3
>> 8
```

If you are performing arithmetic operations (+, −, ×, ÷) on two vectors and one of the vectors contains non-numeric variables, you will get the "non-numeric argument to binary operator". Use `as.numeric()`

on the non-numeric vector to solve this problem.

Here is an example.

```
# 👇️ create a data frame
store <- data.frame(revenue = c(50, 35, 46, 98),
costs = c("23", "12", "23", "49"))
# view the data frame
store
revenue costs
50 23
35 12
46 23
98 49
```

Let's try to create a new column called `profit`

by subtracting `costs`

from `revenue`

.

```
# ⛔️ Error: non-numeric argument to binary operator
store$profit = store$revenue - store$costs
```

It yields an error because the numbers in `costs`

are stored as a `character`

, not as numbers. We cannot subtract a character from a number. You can check the class type of each column.

```
# 👇️ check the class type of each column
class(store$revenue)
>> "numeric"
class(store$costs)
>> "character"
```

The solution is to convert the characters in `costs`

into numbers by using `as.numeric()`

.

```
# 👇️ convert `costs` into a numeric class
# ✅ this runs
store$profit <- store$revenue - as.numeric(store$costs)
```

The R error, "non-numeric argument to binary operator" occurs when you try to perform a binary, or arithmetic, operation (+, −, ×, ÷) on two vectors, and one of the vectors is non-numeric, or on variables that are non-numeric. Use `as.numeric()`

to convert numbers formatted as a character into a number.

Related tutorials curated for you

Error in file(file, "rt") : cannot open the connection

Non-numeric argument to binary operator error in R

R: the condition has length > 1 and only the first element will be used

$ operator is invalid for atomic vectors in R

Error in plot.new() : figure margins too large