# Prefix operators in R

September 11, 2019

Fair warning: This post is about an interesting feature of the R language, it likely won’t help in your data analysis, wrangling or dataviz… but that doesn’t stop it from being at least quite interesting.

Earlier today we were spelunking through the `add_tally()` function from `{dplyr}` and came across this wonderful line of code:

``mutate(x, `:=`(!!name, !!n))``

That’s an example of using prefix notation for something that we would normally write with infix notation. Let’s compare the two:

infix notation

``mutate(x, !!name := !!n)``

prefix notation

``mutate(x, `:=`(!!name, !!n))``

Hadley Wickham makes clear in his Advanced R book that most functions in R are written in prefix notation, e.g. `paste("hello", "world")` and `rep("hello world", 4)`. There are only a small number of built in functions that have a infix operator, and most of them are arithmetic operators.

Now we know how to re-write an infix operator in prefix notation, we can do something fairly special; we can swap the operator programmatically. Let’s create a function where we can change the arithmetic operator applied to the first two weird numbers:

``swappable_operator <- function(prefix){prefix(70, 836)}``

Now we can give any of the infix operators as the argument for our function:

``````swappable_operator(`+`)
##  906
swappable_operator(`-`)
##  -766
swappable_operator(`*`)
##  58520``````

That’s quite fun, but there’s not that much benefit to writing R code like this. However, in some other programming languages the ability to use prefix notation is incredibly useful. From 2012 - 2015 I was a Mathematica consultant for Wolfram Research and would use the following construction at least every other day:

``````(*This is Wolfram Language code, NOT R*)
Accumulate@{1,2,4,16}``````

If anyone does have a good application for this prefix operator, please do let me know by replying to my tweet: