Digging into a not so special type of R functions, in order to make an emoji-pizza-dplyr-slice one.
What are infix functions?
In R, most of the functions are “prefix” - meaning that the function name comes before the arguments, which are put between parentheses :
fun(a,b). With infix functions, the name comes between the arguments
a fun b. In fact, you use this type on a daily basis with
+, and so on.
So, how can you create your own infix functions?
As an R user (and even if you come from another language), you’re used to write your functions in this form :
But if your function has only two operators, you can write it this way :
At this point, you’ve noticed two things :
Back ticks are R way to denote a special name. You can in fact put any characters between them (even emoji, as we’ll see later on):
% surrounding the function name are necessary if you want to create your own infix functions. As
% is a special character, you need to use it inside back ticks. Note that basic infix functions in R don’t need the percent sign, but user generated one do.
Good thing (or maybe not) is that you can override the default functions, if you want to drive someone mad:
This first function does nothing but printing the time twice, with 3 seconds of pause in-between. Needless to say that’s useless, but that was just an example :)
Let’s do something more tidyverse friendly. For example, let’s try a function
%select% which will be the equivalent to
And now, the cool stuffs
You can use (almost) any character you like between the two
%, except %, of course. But… really ANYTHING? Because, you know, sometimes you just need to make some pizza function calls, or maybe you just like emojis.
So, anybody has some spare time to recode the whole tidyverse in emojis? 😃
More on infix functions :