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.
%>%, 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.
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:
And we’ll use a function for each key verb:
bop(). Using this object and these verbs, there are (at least) four
ways we could retell the story in code:
Save each intermediate step as a new object. ...