What is |> Pipe Operator in R: Simple Explanation and Usage
|> pipe operator in R passes the result of one expression as the first argument to the next function, making code easier to read and write. It helps chain commands in a clear, step-by-step way without nested parentheses.How It Works
The |> pipe operator in R takes the output of the expression on its left and sends it as the first input to the function on its right. Think of it like a conveyor belt passing a box from one worker to the next, where each worker does something to the box before passing it along.
This lets you write code in a straight line, reading from left to right, instead of nesting functions inside each other. It makes your code look cleaner and easier to understand, especially when you have many steps to do in order.
Example
This example shows how to use |> to take a number, add 5, then multiply by 2, step by step.
result <- 10 |> ( function(x) x + 5 ) |> ( function(x) x * 2 ) print(result)
When to Use
Use the |> pipe when you want to write clear, readable code that applies multiple functions in sequence. It is great for data cleaning, transformation, or any process where you do one step after another.
For example, when working with data frames, you can filter rows, select columns, and summarize data all in one smooth chain. This reduces confusion and makes your code easier to maintain.
Key Points
|>passes the left side result as the first argument to the right side function.- It improves code readability by avoiding nested parentheses.
- Introduced in R 4.1.0 as a base pipe operator.
- Works well for chaining simple functions and data transformations.