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.