The magrittr package is a great resource for making R more readable… and more writable.
Here’s an example of hard-to-read code
If you came across that in someone else’s code, you might gag. And rightly so. It takes a few moments to work out what’s going on: print the first five characters of the reverse of the upper case of the letters of the alphabet. Not very readable. If an entire R programme comprises lines like that, you might just chuck it in for good. But magrittr offers us another way: piping an object into a function using the
letters %>% toupper() %>% rev() %>% head() %>% print()
It’s longer. But the whitespace hopefully makes is more readable. I think so.
Another thing that helps, is that the syntactic and logical orders of the functions are the same. What I mean here is that the order in which the functions appear is also the order they are processed in. So here, you take the letters of the alphabet, upper case them, reverse it, take the first five characters, then print it.
It’s even more readable if you spread it all out over several lines:
There should be no doubt at all what’s going on. Very readable. And, more writable: suppose you forgot something. The above code snippets all produce the result Z Y X W V. But what if your output was meant to look like this: Z26 Y25 X24 W23 V22? In the first snippet, you would need to dig into those nested brackets and come up with
Ugh. But with pipe operator, it’s easy:
I hope you agree that inserting a line into the logical order of the transformations you’re performing is a lot easy than delving into those brackets. For this reason, the code I use in this blog will tend to use magrittr pipes a lot. The magrittr manual details several variations on the theme, including
%T>%, which I use quite a bit too.