The Pipe — Reading Code Left to Right
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).
The shortcut
To turn nested code into a pipe, find the innermost value, then list the functions from the inside out. Each function keeps its other arguments in its own brackets.
Find the innermost value
The deepest thing in the brackets is
kg. The chain starts there.
The pipe does not make code faster or slower. It only changes the order you read it in, which is the whole point.
Drills
Answer fast — trust the rule.
kg |> sum() is the same as which call?
kg |> round(1) is the same as which call?
What does kg |> sort(decreasing = TRUE) |> head(2) return?
Why is kg |> mean an error?
Which of these is the magrittr pipe used throughout older tidyverse code?
Remember
x |> f(y)meansf(x, y): the left side becomes the first argument.- Shortcut: start from the innermost value and list the functions from the inside out.
- Trap: every step needs its brackets, as in
mean(), notmean.
