0
0
R Programmingprogramming~5 mins

Pipe operator (%>% and |>) in R Programming

Choose your learning style9 modes available
Introduction

The pipe operator helps you write code that reads like a recipe. It passes the result of one step directly into the next step, making your code easier to follow.

When you want to apply multiple functions one after another on some data.
When you want to avoid creating many temporary variables.
When you want your code to look like a clear sequence of actions.
When working with data frames and you want to filter, transform, and summarize data step-by-step.
When you want to improve readability by writing code from left to right.
Syntax
R Programming
data %>% function1() %>% function2()

# or using native pipe in R 4.1+
data |> function1() |> function2()

The %>% operator comes from the dplyr package (part of tidyverse).

The |> operator is built into R version 4.1 and later.

Examples
This example filters cars with 6 cylinders and then calculates the average miles per gallon.
R Programming
library(dplyr)

mtcars %>%
  filter(cyl == 6) %>%
  summarise(avg_mpg = mean(mpg))
This uses the native pipe to select cars with 4 cylinders, add a new column converting mpg to kilometers per liter, and then shows the first few rows.
R Programming
mtcars |> 
  subset(cyl == 4) |> 
  transform(kpl = mpg * 0.425144) |> 
  head()
Sample Program

This program filters cars with 4 gears, converts weight from 1000 lbs to tons, then calculates the average weight in tons.

R Programming
library(dplyr)

result <- mtcars %>%
  filter(gear == 4) %>%
  mutate(weight_tons = wt / 2) %>%
  summarise(avg_weight = mean(weight_tons))

print(result)
OutputSuccess
Important Notes

Remember to load dplyr to use %>%.

The native pipe |> does not require extra packages but works slightly differently in some cases.

Using pipes makes your code easier to read and write, especially for data transformations.

Summary

The pipe operator passes the output of one function to the next.

%>% is from dplyr, |> is built-in from R 4.1.

Pipes help write clear, step-by-step code for data tasks.