Most of the operators that we use in R are binary operators (having two operands). Hence, they are infix operators, used between the operands. Actually, these operators do a function call in the background.
For example, the expression a+b
is actually calling the function `+`()
with the arguments a
and b
, as `+`(a, b)
.
Note: The backtick (`
), this is important as the function name contains special symbols.
Following are some example expressions along with the actual functions that get called in the background.
Example: How infix operators work in R?
We can perform arithmetic operations using infix operators like +
, -
, and *
.
Here are the calculations we can perform using both the usual notation and the alternative notation with backticks:
# addition operation
5+3
`+`(5,3)
# subtraction operation
5-3
`-`(5,3)
# multiplication and subtraction operation
5*3-1
`-`(`*`(5,3),1)
Output
[1] 8 [1] 8 [1] 2 [1] 2 [1] 14 [1] 14
In the above example,
For Addition Operation:
- Usual notation:
5 + 3 = 8
- Alternative notation:
`+`(5,3) = 8
For Subtraction Operation:
- Usual notation:
5 - 3 = 2
- Alternative notation:
`-`(5,3) = 2
For Multiplication and Subtraction Operation:
- Usual notation:
5 * 3 - 1 = 14
- Alternative notation:
`-`(`*`(5,3),1) = 14
User defined infix operator
It is possible to create user-defined infix operators in R. This is done by naming a function that starts and ends with %
.
Following is an example of a user-defined infix operator to see if a number is exactly divisible by another.
`%divisible%` <- function(x, y) {
if (x %% y == 0)
return(TRUE)
else
return(FALSE)
}
10 %divisible% 3
10 %divisible% 2
`%divisible%`(10,5)
Output
[1] FALSE [1] TRUE [1] TRUE
This function can be used as an infix operator a %divisible% b
or as a function call `%divisible%`(a, b)
. Both are the same.
Note: Things to remember while defining your own infix operators are that they must start and end with %
. Surround it with backtick (`
) in the function definition and escape any special symbols.