How to Use the Pipe Operator in R (With Examples) (2024)

by Zach BobbittPosted on July 22, 2022

You can use the pipe operator (%>%) in R to “pipe” together a sequence of operations.

This operator is most commonly used with the dplyr package in R to perform a sequence of operations on a data frame.

The basic syntax for the pipe operator is:

df %>% do_this_operation %>% then_do_this_operation %>% then_do_this_operation ...

The pipe operator simply feeds the results of one operation into the next operation below it.

The advantage of using the pipe operator is that it makes code extremely easy to read.

The following examples show how to use the pipe operator in different scenarios with the built-in mtcars dataset in R.

#view first six rows of mtcars datasethead(mtcars) mpg cyl disp hp drat wt qsec vs am gear carbMazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

Example 1: Use Pipe Operator to Summarize One Variable

The following code shows how to use the pipe (%>%) operator to group by the cyl variable and then summarize the mean value of the mpg variable:

library(dplyr)#summarize mean mpg grouped by cylmtcars %>% group_by(cyl) %>% summarise(mean_mpg = mean(mpg))# A tibble: 3 x 2 cyl mean_mpg 1 4 26.72 6 19.73 8 15.1

From the output we can see:

  • The mean mpg value for the cars with a cyl value of 4 is 26.7.
  • The mean mpg value for the cars with a cyl value of 6 is 19.7.
  • The mean mpg value for the cars with a cyl value of 8 is 15.1.

Notice how easy the pipe operator makes it to interpret the code as well.

Essentially, it says:

  • Take the mtcars data frame.
  • Group it by the cyl variable.
  • Then summarize the mean value of the mpg variable.

Example 2: Use Pipe Operator to Group & Summarize Multiple Variables

The following code shows how to use the pipe (%>%) operator to group by the cyl and am variables, and then summarize the mean of the mpg variable and the standard deviation of the hp variable:

library(dplyr)#summarize mean mpg and standard dev of hp grouped by cyl and ammtcars %>% group_by(cyl, am) %>% summarise(mean_mpg = mean(mpg), sd_hp = sd(hp))# A tibble: 6 x 4# Groups: cyl [3] cyl am mean_mpg sd_hp 1 4 0 22.9 19.7 2 4 1 28.1 22.7 3 6 0 19.1 9.184 6 1 20.6 37.5 5 8 0 15.0 33.4 6 8 1 15.4 50.2 

From the output we can see:

  • For cars with a cyl value of 4 and am value of 0, the mean mpg value is 22.9 and the standard deviation of the hp value is 19.7.
  • For cars with a cyl value of 4 and am value of 1, the mean mpg value is 28.1 and the standard deviation of the hp value is 22.7.

And so on.

Once again, notice how easy the pipe operator makes it to interpret the code as well.

Essentially, it says:

  • Take the mtcars data frame.
  • Group it by the cyl and the am variables.
  • Then summarize the mean value of the mpg variable and the standard deviation of the hp variable.

Example 3: Use Pipe Operator to Create New Variables

The following code shows how to use the pipe (%>%) operator along with the mutate function from the dplyr package to create two new variables in the mtcars data frame:

library(dplyr)#add two new variables in mtcarsnew_mtcars <- mtcars %>% mutate(mpg2 = mpg*2, mpg_root = sqrt(mpg))#view first six rows of new data framehead(new_mtcars) mpg cyl disp hp drat wt qsec vs am gear carb mpg2 mpg_root1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 42.0 4.5825762 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 42.0 4.5825763 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 45.6 4.7749354 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 42.8 4.6260135 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 37.4 4.3243506 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 36.2 4.254409

From the output we can see:

  • The new mpg2 column contains the values of the mpg column multiplied by 2.
  • The new mpg_root column contains the square root of the values in the mpg column.

Once again, notice how easy the pipe operator makes it to interpret the code as well.

Essentially, it says:

  • Take the mtcars data frame.
  • Create a new column called mpg2 and a new column called mpg_root.

Related: How to Use the transmute() Function in dplyr

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use the Tilde Operator (~) in R
How to Use Dollar Sign ($) Operator in R
How to Use “NOT IN” Operator in R
How to Use %in% Operator in R

How to Use the Pipe Operator in R (With Examples) (2024)

FAQs

How to use pipe operator in RStudio? ›

R pipes are a way to chain multiple operations together in a concise and expressive way. They are represented by the %>% operator, which takes the output of the expression on its left and passes it as the first argument to the function on its right. Using pipes in R allows us to link a sequence of analysis steps.

What does %>% in RStudio? ›

The pipe operator, formerly written as %>% , was a longstanding feature of the magrittr package for R. The new version, written as |> , is largely the same. It takes the output of one function and passes it into another function as an argument. This allows us to link a sequence of analysis steps.

What is the difference between |> and %>% in R? ›

$x, . $y)} is equivalent to split(df$x, df$y) . %>% allows you to drop the parentheses when calling a function with no other arguments; |> always requires the parentheses.

What does the Tidyverse pipe operator %>% do? ›

Use %>% to emphasise a sequence of actions, rather than the object that the actions are being performed on. Avoid using the pipe when: You need to manipulate more than one object at a time. Reserve pipes for a sequence of steps applied to one primary object.

How to type %>% in R? ›

In RStudio the keyboard shortcut for the pipe operator %>% is Ctrl + Shift + M (Windows) or Cmd + Shift + M (Mac).

How does pipe () work? ›

A pipe simply refers to a temporary software connection between two programs or commands. An area of the main memory is treated like a virtual file to temporarily hold data and pass it from one process to another in a single direction. In OSes like Unix, a pipe passes the output of one process to another process.

What does %>% mean IR? ›

Pipe (%>%) Operator. The principal function provided by the magrittr package is %>% , or what's called the “pipe” operator. This operator will forward a value, or the result of an expression, into the next function call/expression.

What does the pipe operator do? ›

The pipe operator reduces the coding load of saving intermediate results that will only be referencing in next line of code. This reduction in managing intermediate results can make your code easier to read.

What does %>% mean in Ggplot? ›

the %>% is a pipe operator that is actually part of the dplyr library (along with the filter function) not from the ggplot2 library. To sample 1%, there is a sample_frac function in the dplyr library. It would be something like (df %>% sample_frac(0.01))

Why would you want to use pipes instead of nested functions in R? ›

Pipes make it easier to read long sequences of functions. Pipes allow you to combine more functions in a single sequence. Pipes make it easier to add or remove functions.

Why new pipe in R? ›

Since R is prone to expressions with many nested parentheses, piping allows one to reason about code from left to right (as when writing in English), instead of right to left with many nested parentheses (see example below). From the {magrittr} documentation, the pipe's usage is thus: LHS %>% RHS .

What is the |> symbol in R? ›

|> is the base R "pipe" operator. It was new in version 4.1. 0. In brief, the pipe operator provides the result of the left hand side (LHS) of the operator as the first argument of the right hand side (RHS).

What package is the pipe operator in R? ›

The pipe, %>% , comes from the magrittr package by Stefan Milton Bache. Packages in the tidyverse load %>% for you automatically, so you don't usually load magrittr explicitly.

Why is the pipe function not working in R? ›

Problem: not all functions are pipe-friendly

{magrittr} pipes work best with functions written to be "pipe-friendly." These generally take a dataframe as a first argument, and may use data masking to let you refer to columns within that dataframe without prefixing them. e.g., many {dplyr} verbs are pipe-friendly.

What is the use of pipe? ›

A pipe is a tubular section or hollow cylinder, usually but not necessarily of circular cross-section, used mainly to convey substances which can flow — liquids and gases (fluids), slurries, powders and masses of small solids.

How do you use pipe command? ›

The | command is called a pipe. It is used to pipe, or transfer, the standard output from the command on its left into the standard input of the command on its right.

How do you type the pipe operator? ›

If you still cant find | you can get it by using your number pad on your keyboard and alt. (make sure you have Number Lock on). So to get the symbol | you hold down alt then while holding it down put in 124 (on your number pad) and let go of alt .

How do I run R code line by line in RStudio? ›

Executing a single line

To execute the line of source code where the cursor currently resides press the Ctrl+Enter keys (or use the Run toolbar button): After executing the line of code, RStudio automatically advances the cursor to the next line. This enables you to single-step through a sequence of lines.

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5963

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.