The Pipe — Reading Code Left to Right
The native pipe passes the value on its left as the first argument of the function call on its right, so nested calls can be written as a left-to-right chain.
Follow data through a sequence of transformations and identify each stage's result.
You want to take the harvest weights, summarise them, transform the summary and round it for the newsletter. Written as nested calls, the code reads inside out: the first thing that happens sits in the middle of the line. The pipe lets you write the same steps in the order they happen, like a recipe.
The rule
x |> f(y)meansf(x, y): the left side becomes the first argument.
The native pipe |> arrived in R 4.1. It takes the value on its left and passes it as the first argument of the function call on its right. Chain several and each result flows into the next step.
kg <- c(12.5, 8, 15, 3.5, 6)
# nested: read from the inside out
round(sqrt(mean(kg)), 1)
# piped: read from left to right
kg |> mean() |> sqrt() |> round(1) # [1] 3Both lines compute the same thing: the mean is 9, its square root is 3, rounded to one decimal place it is 3. In the piped version, round(1) receives the square root as its first argument, and the 1 becomes its second argument, the number of digits.
A longer chain reads like a to-do list:
kg |>
sort(decreasing = TRUE) |> # 15.0 12.5 8.0 6.0 3.5
head(3) # 15.0 12.5 8.0Rules that trip people up:
- The right side must be a call with brackets.
kg |> mean()works;kg |> meanis a syntax error. - Break long chains after the pipe, one step per line, so each line is one action.
- Need the value somewhere other than first? Since R 4.2 you can name that argument and use
_as a placeholder.grepl()takes the pattern first and the text second, soc("tomato", "bean") |> grepl("to", x = _)asks whether each name contains "to" and returns TRUE FALSE. Most of the time you will not need it.
You will also meet %>%, the older pipe from the magrittr package that the tidyverse made famous. It behaves almost the same way; it also accepts kg %>% mean without brackets and uses . as its placeholder. New code can use |>, which needs no package. RStudio and Positron insert a pipe with Ctrl+Shift+M (Cmd+Shift+M on a Mac).