I would like to build a function like the following:
function(x, y, operador)
The idea is that it receives an operator, for example: +
, -
, *
. /
and can return the result of applying the same between x
ey
I would like to build a function like the following:
function(x, y, operador)
The idea is that it receives an operator, for example: +
, -
, *
. /
and can return the result of applying the same between x
ey
Something fantastic about R is that operators are functions like any other, a little more particular that is. They are known as binary functions since they are limited to only two parameters or they are also called infix operators since they allow infix notation .
To be able to write an operation with an infix notation, you have to use "backticks", example:
So the function could end up looking like this:
and the execution of it could be:
It is important to note that there are many more infix operators that we can use using this technique:
arithmetic
Comparatives
logical
Note : the negation
!
ornot
is a special case as it only expects one parameter:Assignment
Note: Although the assignment is an infix operator like the others, it collides with certain particularities that have to do with how the parameters of a function are evaluated, which results in it
aplicar()
not working the way it does with the rest of the operators. .