2026-11-16
Learn how to use the pipe operator (|>) to write more readable code.
We want to process mtcars:
cyl >= 6
am
Two common approaches: intermediate objects or nested calls.
Overwrite the same object at each step:
res means renaming every occurrence.Use temporary names:
Run all calls at once:
No intermediate objects, but we must read from the inside out.
|>
The pipe passes the output of the left-hand side to the next call:
Read it as “and then”:
|>
|> is available since R 4.1 (2021).
We can also assign at the end of the chain with ->:
_
grepl() takes the vector to check in second position:
_
_ tells the piped data where to go:
_
Available since R 4.2 (2022).
Must be used with a named argument:
Named functions are defined first and can be used multiple times:
Anonymous functions are created on the fly and can only be used once:
%>%?%>% vs |>
%>% comes from the magrittr package.tidyverse.|> in base R.For simple cases, both behave the same.
We recommend |> since it is always available, and doesn’t require an extra package.