Skip to the workspace
Pebellslearn by building
Basic Syntax  ›  Lesson

The Pipe — Reading Code Left to Right

Pipe 10 minThe 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.

r programming / The Pipe — Reading Code Left to Right

Explore each scene at your own pace.

01 · The rule

The rule

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) means f(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] 3

Both 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.0

Rules that trip people up:

  • The right side must be a call with brackets. kg |> mean() works; kg |> mean is 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, so c("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).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.