by Guangming Lang
~1 min read

Categories

  • r

Infix functions are functions where the function name comes in between its arguments when used. For example, operators like + and - are actually infix functions. Conversely, you can think of infix functions as operators. Here’s an example of an infix function that concatenate two vectors.

`%&%` <- function(x, y) { 
        # @x, @y: vectors or sigle values
        # returns: this function concatenates @x and @y without space in between
        paste(x, y, collape="", sep="")
}

To use it, we simply treat it as any other operators.

"data" %&% "analysis"
## [1] "dataanalysis"
"cabaceo" %&% 1:5
## [1] "cabaceo1" "cabaceo2" "cabaceo3" "cabaceo4" "cabaceo5"

Here’s another example of an infix function that allows you to return a default value when encountering NULL. This is very helpful when used inside of another function to avoid returning a NULL value.

`%||%` = function(a, b) if (!is.null(a)) a else b

100 %||% NA
## [1] 100
NULL %||% NA
## [1] NA