This is not a pipe
I, like the rest of our team, frequently use the R language for statistical analysis for various projects. One really cool feature of R is that it has a vibrant user community and contributors. I was working on some analysis last week and saw an example using the ‘pipe’ operator %>% along with a lot of ‘buzz’ on sites like Stack Overflow and R Bloggers. I have to admit at first, I was resistant to a new package and functions, and I simply didn’t ‘get it’. Still, the magritttr package seemed to be changing the way people wrote functions in R.
I tried it – mostly to rebut my colleagues who had recommended it. After a few minutes of stumbling around, and much to my shock and amazement, have concluded that they were right!
What does the ‘pipe’ operator do?
The pipe operator does a (deceptively) simple thing. It takes whatever is on the left hand side of the operator, and ‘pipes’ it to the first argument to the right hand side. So, x %>% f() = f(x). The simplest example I can think of is the following:
3 %>% + 2
Big deal, right? Actually, it is a big deal, because you can chain them together! Consider this:
cars %>% subset(speed<50) %>% subset(dist > 10) %>% plot()
Reading from left to right, it is completely obvious even to a non-programmer what was done. And the best part? The ‘cars’ object remains pristine, and no accessory datasets were stored in the process!
Magrittr is a nod to the Belgian painter Rene Margritte, and his painting ‘The Treachery of Images’ (The French at the bottom translates to ‘this is not a pipe’).