Skip to Content
Course content

21: The Pipe Operator in R

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're working at a sandwich shop. To make a sub, you follow a sequence: you grab the bread, then you add the meat, then you add the cheese, then you toast it, and finally, you wrap it. You don't start with the wrapper, put the toaster inside the wrapper, put the cheese inside the toaster, and so on. That would be absurd. You move the sandwich forward through a series of steps.

In R, without the pipe, we often write code that feels like we're building that sandwich from the inside out. It looks like this:

wrap(toast(add_cheese(add_meat(bread))))

It's a mess. To understand what's happening, your brain has to jump to the very center of the parentheses and then read outward. I've spent far too many hours of my career squinting at "nested" functions, trying to count closing parentheses to figure out where one operation ends and the next begins. The pipe operator—%>% (from the magrittr package) or the newer |> (built into base R)—fixes this by letting us write code in the order the actions actually happen.

Reading from Left to Right

The pipe essentially tells R: "Take the result of the previous expression and pass it as the first argument to the next function." It turns that nested sandwich nightmare into a clean assembly line.

Let's look at a real scenario. Suppose you have a dataset of coffee shop sales and you want to find the top-selling drink categories for a specific region. Without a pipe, you'd be nesting filter(), group_by(), and summarize() inside one another. Instead, we do this:

library(dplyr)

top_drinks <- coffee_sales %>% 
  filter(region == "Northwest") %>% 
  group_by(drink_category) %>% 
  summarize(total_revenue = sum(price * quantity)) %>% 
  arrange(desc(total_revenue))

See how that reads? "Take the sales data, then filter for the Northwest, then group by category, then calculate revenue, then sort them." It's a narrative. If I need to change the region to "Southeast," I know exactly which line to edit without worrying about breaking a chain of five closing parentheses at the end of the block.

The Base R Alternative

For a long time, %>% was the gold standard because it came with the Tidyverse. However, R recently introduced the native pipe |>. For about 95% of your daily work, they behave identically. I personally still use %>% out of habit and because it has a few advanced features (like the dot placeholder . for passing data into arguments other than the first one), but you'll see |> popping up more in modern scripts.

Here is a quick comparison of the two. Notice the output is exactly the same:

# The magrittr way
coffee_sales %>% filter(price > 5)

# The native R way
coffee_sales |> filter(price > 5)

The most important thing to remember is that the pipe doesn't change how the functions work; it just changes how you organize them. You're still calling the same functions, but you're presenting them in a way that doesn't make your coworkers (or your future self) want to pull their hair out.




📋 Practical Task

Refactoring the Monthly Weather Analysis

You have been handed a script from a junior analyst that calculates the average temperature for "London" from a dataset called weather_data. The current code is heavily nested and difficult to read:

# The current messy code
result <- summarize(filter(weather_data, city == "London"), avg_temp = mean(temperature))

Your task is to refactor this code using the pipe operator (%>% or |>) to make it more readable. Your final solution should follow the assembly-line logic: start with the data frame, filter for the city, and then calculate the average temperature.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.