Compounding Commands with the Pipe Operator

Learn to use the pipe operator, %>%, in the tidyverse to chain commands into a single line, making them concise and readable.

One of the most powerful pieces of the tidyverse is the pipe operator: %>%. The pipe operator feeds, or “pipes,” the output from one command as the input to the next, taking advantage of the tidyverse function standardization. This allows us to chain multiple commands into a single line, keeping our code concise and readable. Thus, when manipulating data, we can combine many commands without storing intermediate variables between operations. So when someone is reading our code, it will read a little more naturally, like:

  • “Take my survey data, group it by respondent gender, and calculate the mean answer by gender.”

As opposed to:

  • “Take my survey data, group it by respondent gender, save an intermediate variable called survey data by gender, and calculate the answer by gender.”

By using the pipe operator, we’re removing the need for that intermediate “call my data something new” step and going directly to the next step of the data manipulation—the same way we would talk to someone about it. Our code structure is now more flexible; we can organize it in the most readable way rather than basing it on function inputs and outputs.

Let’s take a look at some code:

Get hands-on with 1200+ tech skills courses.