The magrittr package is a great resource for making R more readable… and more writable.

Here’s an example of hard-to-read code

print(head(rev(toupper(letters))))

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 %>% operator:

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:

letters %>%
toupper() %>%
rev() %>%
head() %>%
print()

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

print(head(rev(paste0(toupper(letters), 1:26))))

Ugh. But with pipe operator, it’s easy:

letters %>%
toupper() %>%
paste0(1:26) %>%
rev() %>%
head() %>%
print()

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 %<>% and %T>%, which I use quite a bit too.

Published by densurekalkun

https://twitter.com/GeocacherB

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: