Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
I’ve seen R users swooning over the magrittr
package for a while now, but I couldn’t make heads or tails of all these scary %>%
symbols. Finally I had time for a closer look, and it seems potentially handy indeed. Here’s the idea and a simple toy example.
So, it can be confusing and messy to write (and read) functions from the inside out. This is especially true when functions take multiple arguments. Instead, magrittr
lets you write (and read) functions from left to right.
Say you need to compute the LogSumExp function
In base R, you might write
log(sum(exp(MyData)), exp(1))
But this is a bit of a mess to read. It takes a lot of parentheses-matching to see that the exp(1)
is an argument to log
and not to one of the other functions.
Instead, with magrittr
, you program from left to right:
MyData %>% exp %>% sum %>% log(exp(1))
The pipe operator %>%
takes output from the left and uses it as the first argument of input on the right. Now it’s very clear that the exp(1)
is an argument to log
.
There’s a lot more you can do with magrittr
, but code with fewer nested parentheses is already a good selling point for me.
Apart from cleaning up your nested functions, this approach to programming might be helpful if you write a lot of JavaScript code, for example if you make D3.js visualizations. R’s magrittr
pipe is similar in spirit to JavaScript’s method chaining, so it might make context-switching a little easier.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.