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?
<- arrange(mtcars, gear)
cars_arranged <- slice(cars_arranged, 1:10)
cars_selected
# more compactly
<- slice(arrange(mtcars, gear), 1:10) cars_selected
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:
<- mtcars %>%
cars_selected 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.