Can an operator be passed as a parameter of a function?


I would like to build a function like the following:

function(x, y, operador) 

The idea is that it receives an operator, for example: + , - , * . / y can return the result of applying the same between x and y


Something fantastic about R is that the operators are functions like any other, a little more particular that if. 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 the "backticks", example:

2 + 3 == `+`(2,3)
2 - 3 == `-`(2,3)
2 / 2 == `/`(2,2)
2 * 2 == `*`(2,2)

So the function could end up looking like this:

aplicar <- function(x, y, operador) {

and the execution of it could be:

aplicar(2, 3, `+`)
aplicar(2, 3, `-`)
aplicar(2, 2, `/`)
aplicar(2, 2, `*`)

It is important to note that there are many more infix operators that we can use using this technique:


+   Suma
–   Resta
*   Multiplicación
/   División
^   Exponente
%%  Módulo
%/% División entera


<   Menor a 
>   Mayor a
<=  Menor igual a
>=  Mayor igual a
==  Igual
!=  Distinto


&   Y lógico
&&  Y lógico (no vectorizado)
|   O lógico
||  O lógico (no vectorizado)

Note : denial ! o not is a special case as it only expects one parameter:



<-, <<-, =  Asignación izquierda
->, ->>     Asignación derecha

Note: Although the assignment is an infix operator like the others, it collides with certain peculiarities that have to do with how the parameters of a function are evaluated, which results in aplicar() not working the way it does with the rest of the operators.

Scroll to Top