How to Write Infix Functions in R

Master R

By Guangming Lang Comment

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

To learn more, read the chapter on functions from Hadley’s book, Advanced R.

If you enjoyed this post, get updates. It's FREE