mutate(x, `:=`(!!name, !!n))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 quite interesting.
Earlier today we were spelunking through the add_tally() function from {dplyr} and came across this wonderful line of code:
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 use infix operators, 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(`+`)[1] 906
swappable_operator(`-`)[1] -766
swappable_operator(`*`)[1] 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}
Did you know that #rstats has prefix notation via the backtick?
— finding youR way (@rfindingyourway) September 11, 2019
We only just discovered this today when spelunking through the code for add_tally() in {dplyr} 🧐 pic.twitter.com/doRXUnlu24