Pipe Operator in R: %>% and |> Explained
The pipe lets you write R code in the order you think it: take this data, then do this, then do that. It is the foundation of every other lesson in this dplyr tutorial.
What is the pipe operator?
The pipe operator in R is a symbol that passes the result of one step into the next step. Think of a car wash. The car goes in, gets rinsed, then soaped, then dried. Each station works on what the previous station handed over. A pipe lets you write code the same way.
R has two pipes, and you will see both online:
|>is the native pipe, built into R itself since version 4.1.%>%is the magrittr pipe, which dplyr makes available when you runlibrary(dplyr).
For almost everything in this dplyr tutorial the two behave identically. Start by reading either symbol as the word "then".
The simplest example
Forget data frames for a moment and use plain numbers. This calculates the square root of 16:
sqrt(16)
[1] 4
Here is the same thing with a pipe:
16 |> sqrt()
[1] 4
Same answer. The pipe took 16 from its left and placed it inside sqrt() on its right. Read it as "take 16, then take the square root".
Why bother? Two functions in a row
Now round the square root of 50 to one decimal place. Without a pipe, you nest one function inside another:
round(sqrt(50), 1)
You must read this from the inside out: first sqrt(50), then round(). The order you read is the opposite of the order things happen. With pipes it flows left to right:
50 |> sqrt() |> round(1)
[1] 7.1
"Take 50, then square root, then round to 1 decimal." The code now reads like the instruction. With two functions the difference is small. With six functions, as in real data work, it is huge.
How the pipe works
The rule is short: the value on the left becomes the first argument of the function on the right. Any extra arguments you write stay where they are.
| You write | R runs |
|---|---|
x |> f() | f(x) |
x |> f(y) | f(x, y) |
x |> f(y) |> g(z) | g(f(x, y), z) |
That is why 50 |> sqrt() |> round(1) works. The 50 goes into sqrt(), and the answer goes into round() as its first argument, with 1 as the second.
This rule fits dplyr perfectly. Every dplyr function takes a data frame as its first argument, so you can pipe a data frame through as many functions as you like.
Sample data: ten US cities
The examples below use a small table of the ten largest US cities. You can create it by copying this code into R. The populations are rounded 2020 Census figures, in thousands, so they are good for practice.
library(dplyr)
cities <- tibble(
city = c("New York", "Los Angeles", "Chicago", "Houston", "Phoenix",
"Philadelphia", "San Antonio", "San Diego", "Dallas", "Austin"),
state = c("NY", "CA", "IL", "TX", "AZ", "PA", "TX", "CA", "TX", "TX"),
region = c("Northeast", "West", "Midwest", "South", "West",
"Northeast", "South", "West", "South", "South"),
population_k = c(8804, 3899, 2746, 2305, 1608, 1604, 1435, 1387, 1304, 962)
)
A tibble() is a modern data frame. For this lesson you can treat it as a normal data frame. This is what cities contains:
| city | state | region | population_k |
|---|---|---|---|
| New York | NY | Northeast | 8804 |
| Los Angeles | CA | West | 3899 |
| Chicago | IL | Midwest | 2746 |
| Houston | TX | South | 2305 |
| Phoenix | AZ | West | 1608 |
| Philadelphia | PA | Northeast | 1604 |
| San Antonio | TX | South | 1435 |
| San Diego | CA | West | 1387 |
| Dallas | TX | South | 1304 |
| Austin | TX | South | 962 |
Using the pipe with dplyr
Suppose you only want the cities in Texas. The dplyr function for keeping rows is filter(). You will learn it fully in the dplyr filter lesson. For now, treat it as "keep the rows where this is true". Without a pipe:
filter(cities, state == "TX")
With a pipe:
cities |> filter(state == "TX")
Both give the same result. In the piped version, cities is passed in as the first argument, so you do not write it inside filter() any more.
| city | state | region | population_k |
|---|---|---|---|
| Houston | TX | South | 2305 |
| San Antonio | TX | South | 1435 |
| Dallas | TX | South | 1304 |
| Austin | TX | South | 962 |
One step does not show the real benefit yet. The benefit appears when you add more.
Chaining several steps
The task: find the cities in the South with more than one million people, show only the city name and population, and list the biggest first.
That takes three steps: filter() to keep rows, select() to keep columns (see dplyr select) and arrange() to sort (see dplyr arrange). There are three ways to write it.
Style 1: nested functions
arrange(
select(
filter(cities, region == "South", population_k > 1000),
city, population_k
),
desc(population_k)
)
This works, but you have to start in the middle, at filter(), and work outwards. The sorting instruction sits far from the data it applies to.
Style 2: temporary objects
step1 <- filter(cities, region == "South", population_k > 1000)
step2 <- select(step1, city, population_k)
step3 <- arrange(step2, desc(population_k))
step3
This is readable, but it fills your workspace with throwaway objects, and it is easy to use the wrong one by mistake, for example step1 instead of step2.
Style 3: the pipe
cities |>
filter(region == "South", population_k > 1000) |>
select(city, population_k) |>
arrange(desc(population_k))
| city | population_k |
|---|---|
| Houston | 2305 |
| San Antonio | 1435 |
| Dallas | 1304 |
This is the same result as the other two styles. Austin was dropped by the filter because its population is below 1,000 thousand. Read the pipeline aloud: "Take cities, then keep southern cities over one million, then select city and population, then sort with the largest first."
Notice the layout: each step is on its own line, and each line except the last ends with |>. R sees the trailing pipe and knows the expression continues on the next line.
Saving and finishing a pipeline
Saving the result
A pipeline only prints its result. It does not change cities. To keep the result, assign it to a name at the start:
big_southern_cities <- cities |>
filter(region == "South", population_k > 1000) |>
select(city, population_k) |>
arrange(desc(population_k))
Now big_southern_cities holds the three-row table above, and cities is untouched.
Ending with a single number
A pipeline can end with any function, not only a dplyr one. Here is the average population of the western cities. pull() extracts one column as a plain vector, and mean() averages it:
cities |>
filter(region == "West") |>
pull(population_k) |>
mean()
[1] 2298
That is the mean of Los Angeles (3899), Phoenix (1608) and San Diego (1387). The result is a number in thousands, so the average western city has about 2.3 million people.
%>% vs |>: the two pipes
The magrittr pipe %>% arrived in 2014 and became so popular that R added its own version, |>, in R 4.1.0 (2021). Both work in this tutorial's examples. You can swap one for the other in most dplyr code.
|> native pipe | %>% magrittr pipe | |
|---|---|---|
| Where it comes from | Base R | magrittr package (loaded by dplyr) |
| Minimum R version | 4.1.0 | Any version |
| Parentheses required | Yes: x |> head() | No: x %>% head also works |
| Placeholder for the data | _ (named argument only) | . (any position) |
| Needs a package loaded | No | Yes |
Here is the same pipeline written both ways:
cities |> filter(state == "CA") |> select(city)
cities %>% filter(state == "CA") %>% select(city)
| city |
|---|
| Los Angeles |
| San Diego |
How |> really works
The native pipe is rewritten by R before the code runs. You can see this with quote():
quote(cities |> filter(state == "CA"))
filter(cities, state == "CA")
So |> is not a function. It is just a nicer way to write an ordinary function call.
Sending data to a different argument
By default the data goes into the first argument. Some functions expect the data somewhere else. For example, gsub() wants the text last: gsub(pattern, replacement, x). Both pipes have a placeholder for this case.
With the native pipe, use _ and name the argument:
"Austin, TX" |> gsub(pattern = ", ", replacement = " - ", x = _)
With the magrittr pipe, use .:
"Austin, TX" %>% gsub(", ", " - ", .)
[1] "Austin - TX"
The native placeholder _ needs R 4.2 or later, and it must be given as a named argument (x = _). A more realistic use is a model function, which takes the data in its data argument:
cities |> lm(population_k ~ region, data = _)
Which pipe should you use?
- Learning today on R 4.1 or newer: use
|>. It needs no package and is the future of R. - Working with older R or older code:
%>%works everywhere, and most tutorials, Stack Overflow answers and books still use it. - In a team: match what the team already uses. Do not mix both in one script.
Check your R version with:
R.version.string
In RStudio, the shortcut Ctrl + Shift + M (Windows and Linux) or Cmd + Shift + M (Mac) types the pipe for you. To make it insert |> instead of %>%, go to Tools > Global Options > Code and tick Use native pipe operator.
Style and debugging
Style tips
- Put a space before the pipe and a new line after it.
- Indent every step by two spaces.
- Start with the data frame on its own line.
- Keep pipelines to about 10 steps. Past that, save an intermediate result and continue in a second pipeline.
Debugging a long pipeline
When the result looks wrong, run the pipeline in pieces. Select everything up to a certain line, leaving off the last pipe, and run it. Check what comes out, then add the next line. You can also insert glimpse() in the middle of a pipeline to peek at the data without stopping the flow:
cities |>
filter(region == "South") |>
glimpse() |>
arrange(desc(population_k))
Common pipe errors
| Problem | Cause | Fix |
|---|---|---|
could not find function "%>%" | No package that provides the magrittr pipe is loaded | Run library(dplyr) first, or use |> |
The pipe operator requires a function call as RHS | You wrote cities |> head without parentheses | Write cities |> head() |
unexpected '|>' | The pipe is at the start of a line instead of the end of the previous one | Move the pipe to the end of the line above |
| Plot layers do not appear or code errors | You used a pipe between ggplot2 layers | Use + between layers: cities |> ggplot(aes(city, population_k)) + geom_col() |
| Result is not saved | The pipeline was not assigned | Start with name <- cities |> ... |
Practice exercises
Try each one before opening the answer. Use the cities table from above.
Exercise 1
Rewrite round(sqrt(144), 2) using pipes.
Show answer
144 |> sqrt() |> round(2)
[1] 12
Exercise 2
Show only the city and population of the Northeast cities.
Show answer
cities |>
filter(region == "Northeast") |>
select(city, population_k)
| city | population_k |
|---|---|
| New York | 8804 |
| Philadelphia | 1604 |
Exercise 3
Get the names of cities with more than 2,000 thousand people, from smallest to largest.
Show answer
cities |>
filter(population_k > 2000) |>
arrange(population_k) |>
pull(city)
[1] "Houston" "Chicago" "Los Angeles" "New York"
dplyr FAQ
What does %>% mean in R?
It is the magrittr pipe. It takes the result on its left and passes it as the first argument of the function on its right. dplyr loads it for you.
What is the difference between %>% and |> in R?
%>% comes from the magrittr package and works in any R version. |> is built into R 4.1 and later and needs no package. For everyday dplyr code they behave the same.
Do I need a package to use |> in R?
No. The native pipe is part of base R from version 4.1.0. You only need a package for %>%.
Why does my pipe give "could not find function %>%"?
You have not loaded a package that provides it. Run library(dplyr) or library(magrittr) first, or switch to the native pipe |>.
Can I use the pipe with ggplot2?
Yes, to pass data into ggplot(). Inside the plot, though, add layers with +, not with a pipe.
Does the pipe make R code faster?
No. Its purpose is readability. It removes nested brackets and temporary variables.
Key points
- The pipe passes the left side into the first argument of the function on the right.
- Read it as "then". Code runs in the same order you read it.
|>is built into R 4.1+.%>%comes with dplyr and works everywhere.- Put each step on its own line, ending with the pipe.
- Assign the pipeline to a name to keep the result.
- Use
_or.to send data to an argument other than the first.
Next, learn how to choose columns with dplyr select, then rows with dplyr filter. If anything in R still feels unfamiliar, revisit the R basics lessons.