2.5 Designed for the pipe

The pipe operator, %>%, comes from the magrittr package by Stefan Milton Bache, and is used to chain together a sequence of R functions. More specifically, the pipe operator uses the value of the object on the left-hand side of the operator as the first argument on the operator’s right-hand side.

The pipe allows for highly readable code. Consider wanting to sort the mtcars dataset by the number of gears (gear) and then select the first ten rows. How would you do that?


cars_arranged <- arrange(mtcars, gear)
cars_selected <- slice(cars_arranged, 1:10)

# more compactly
cars_selected <- slice(arrange(mtcars, gear), 1:10)

Using the pipe to substitute the left-hand side of the operator with the first argument on the right-hand side, we can get the same result as follows:

cars_selected <- mtcars %>%
  arrange(gear) %>%
  slice(1:10)

This approach with the pipe works because all the functions return the same data structure (a tibble/data frame) which is the first argument of the next function.

Whenever possible, create functions that can be incorporated into a pipeline of operations.