How to understand binary operator?

# Assign a value to the variable my_apples
my_apples <- 5 

# Fix the assignment of my_oranges
my_oranges <- "six" 

# Create the variable my_fruit and print it out
my_fruit <- my_apples + my_oranges 
my_fruit

The error message is: non-numeric argument to binary operator. I am curious that what binary operator mean here.

In R, you can't add a character variable, the binary operator + is an arithmetic operator. It only works for numeric variables. What are you trying to do? Perhaps this will work:

# Assign a value to the variable my_apples
my_apples <- 5 

# Fix the assignment of my_oranges
my_oranges <- "six" 

# Create the variable my_fruit and print it out
my_fruit <- paste0(my_apples, my_oranges )
my_fruit
#> [1] "5six"

Created on 2020-07-18 by the reprex package (v0.3.0)

1 Like

A binary operator is an operator that takes exactly two operands such as +, -, * etc. Even when you supply more than two operands, the function operates in pairs.

# With two operands.

# This is an example of an infix function since the function comes between the
# arguments.
1 + 2
#> [1] 3

 # But it can be written in prefix form.
`+`(1, 2)
#> [1] 3


# With three operands.

1 + 2 + 3
#> [1] 6

# This doesn't work because `+` only accepts two arguments.
`+`(1, 2, 3)
#> Error in `+`(1, 2, 3): operator needs one or two arguments

# Arguments must be supplied pair-wise.
`+`(`+`(1, 2), 3)
#> [1] 6

Created on 2020-07-19 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.