2 min read

Looking Both Ways - Infix Functions

In your R journeys you may have come across some interesting functions like apply statements or even lm. One function that is particularly helpful (and interesting) is the piping operator (%>%) from the magrittr pacakge. You may have noticed that the piping operator is similar to the matrix multiplcation operator %*%, in that they are both sandwitch functions (may or may not be trying to coin this term right now), as the function call is/are a symbol(s) enclosed by a % on both times. These sandwitch functions in R are actually members of a larger class of functions, known as infix functions. Unlike most functions such as mean(), summary(), or kable(), are prefix functions, which take their arguments after the fucntion is called (mean(c(1.2,1.6,0.4,3.1)). Infix fuctions on the other hand, come inbetween its (two) arguments. Other infix functions include basic addition, and subtraction (+, -) and all your other common aresthmatic functions. Many in R however, are functions enclosed by a % on both side to indicate their special features. Some other examples are %*% (matrix multiplication), or %in%, etc.

For example:

matrix(c(1:4),2) %*% matrix(c(1,0,0,1),2)
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4

We can even define our own infix functions as follows:

`%+2%` <- function(x, y){
return(x + y + 2)

So, what would 1 %+2% 1 result in?

In short, while these functions are, deep down, just regular functions. They can improve readability considerably in your code - imagine needing to use add(x,y) whenever you had to find the sum of two numbers.

(2+2) * 10 - 6 would turn into subtract(multiply(add(2,2),10),6). What a monster!