When using R
you almost certainly have used binary operators.
The syntax contains special binary operators that you use without them
appearing special in any way.
3 + 5
## [1] 8
Here, +
is a binary function that is special in the way that its
arguments are written around the function name and the function is an infix.
You could also write:
`+`(3, 5)
## [1] 8
Leading to the same result. But please, never even consider thinking about writing code like that outside of toy examples, as it it hard to read and really uncommon to write code like that.
This kind of notation works with pretty much all of the syntax in R.
`<-`(x, 1)
x
## [1] 1
`==`(x, 1)
## [1] TRUE
At the end of the day all of those functions are just treated in a special
way by the parser so you can use them in a convenient manner (and yes,
finding useful documentation by calling for example ?`==`
works).
Now, you might be tempted to create some of that useful syntax yourself. Well, there are good news and bad news. The good news is that you can indeed create your own binary functions which work as infix, the bad news is that there are some limitations.
For example you might have noticed that something like this, does not work:
x = c(1:10) data.frame y = rnorm(10)
## Error: <text>:1:13: unexpected symbol
## 1: x = c(1:10) data.frame
## ^
Now, you might think that the above attempt is a bit nonsensical, but
given that both +(1, 2)
and 1 + 2
work, I do not think attempting the above
is that far fetched.
However, R does not automatically place arguments surrounding a function
into a function outside of the few special functions for which this behaviour
is defined.
Outside of the functions which allow this by default you need the %
operator to define binary functions which allow infix notation.
You might have come across things like %in%
, %*%
and %>%
using that kind
of syntax.
You can use it for your own functions as well.
`%plus%` <- function(x, y) {
x + y
}
5 %plus% 10
## [1] 15
Obviously our new %plus%
function does not add much value, but it illustrates
the creation of binary functions allowing infix notation rather nicely.
Note that you need backticks surrounding your function name when defining it,
due to the %
having special meaning and the name %plus%
technically not
being a valid name in R.
In summary, all the operators you use on a daily basis in R are just regular
functions that are treated in a special way by the parser.
You can write your own, but need to surround the name in %
signs to
enable the infix behaviour.