Chapter 14. Pipes with magrittr

Introduction

Pipes are a powerful tool for clearly expressing a sequence of multiple operations. So far, you’ve been using them without knowing how they work, or what the alternatives are. Now, in this chapter, it’s time to explore the pipe in more detail. You’ll learn the alternatives to the pipe, when you shouldn’t use the pipe, and some useful related tools.

Prerequisites

The pipe, %>%, comes from the magrittr package by Stefan Milton Bache. Packages in the tidyverse load %>% for you automatically, so you don’t usually load magrittr explicitly. Here, however, we’re focusing on piping, and we aren’t loading any other packages, so we will load it explicitly.

library(magrittr)

Piping Alternatives

The point of the pipe is to help you write code in a way that is easier to read and understand. To see why the pipe is so useful, we’re going to explore a number of ways of writing the same code. Let’s use code to tell a story about a little bunny named Foo Foo:

Little bunny Foo Foo Went hopping through the forest Scooping up the field mice And bopping them on the head

This is a popular children’s poem that is accompanied by hand actions.

We’ll start by defining an object to represent little bunny Foo Foo:

foo_foo <- little_bunny()

And we’ll use a function for each key verb: hop(), scoop(), and bop(). Using this object and these verbs, there are (at least) four ways we could retell the story in code:

  • Save each intermediate ...

Get R for Data Science now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.