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

The non-numeric argument to binary operator error occurs in R when you “perform arithmetic operations(such as +, -, *, etc.) on non-numeric elements”.

Reproduce the error

a <- "21"
b <- 19
c <- a + b

print(c)

Output

Error in a + b : non-numeric argument to binary operator

In the above code, the variable “a” is a character, and “b” is numeric, so when we try to add them together, R will generate an error message because we are trying to add a character and a numeric.

The error is raised if one or both arguments passed to the operator are not of a numeric data type (e.g., character or logical).

How to fix Error: non-numeric argument to binary operator

To fix the Error: non-numeric argument to a binary operator in R, you can use the “as.numeric()” function to the character to a numeric vector.

Example 1

a <- "21"
b <- 19
c <- as.numeric(a) + b

print(c)

Output

[1] 40

Example 2

# Create dataframe
df <- data.frame(
  "Cars" = c("BMW", "AUDI", "MERCEDEZ"),
  "Mileage" = c(10, 15, 18),
  "Airbags" = c("4", "4", "6")
)

# Attempt to create new column called 'total'
df$total <- df$Mileage + as.numeric(df$Airbags)
print(df)

Output

  Cars    Mileage  Airbags  total
1 BMW       10        4      14
2 AUDI      15        4      19
3 MERCEDEZ  18        6      24

That’s it.

Leave a Comment