R Language Pipe operators (%>% and others)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Pipe operators, available in magrittr, dplyr, and other R packages, process a data-object using a sequence of operations by passing the result of one step as input for the next step using infix-operators rather than the more typical R method of nested function calls.

Note that the intended aim of pipe operators is to increase human readability of written code. See Remarks section for performance considerations.

Syntax

  • lhs %>% rhs # pipe syntax for rhs(lhs)

  • lhs %>% rhs(a = 1) # pipe syntax for rhs(lhs, a = 1)

  • lhs %>% rhs(a = 1, b = .) # pipe syntax for rhs(a = 1, b = lhs)

  • lhs %<>% rhs # pipe syntax for lhs <- rhs(lhs)

  • lhs %$% rhs(a) # pipe syntax for with(lhs, rhs(lhs$a))

  • lhs %T>% rhs # pipe syntax for { rhs(lhs); lhs }

Parameters

lhsrhs
A value or the magrittr placeholder.A function call using the magrittr semantics

Remarks

Packages that use %>%

The pipe operator is defined in the magrittr package, but it gained huge visibility and popularity with the dplyr package (which imports the definition from magrittr). Now it is part of tidyverse, which is a collection of packages that "work in harmony because they share common data representations and API design".

The magrittr package also provides several variations of the pipe operator for those who want more flexibility in piping, such as the compound assignment pipe %<>%, the exposition pipe %$%, and the tee operator %T>%. It also provides a suite of alias functions to replace common functions that have special syntax (+, [, [[, etc.) so that they can be easily used within a chain of pipes.

Finding documentation

As with any infix operator (such as +, *, ^, &, %in%), you can find the official documentation if you put it in quotes: ?'%>%' or help('%>%') (assuming you have loaded a package that attaches pkg:magrittr).

Hotkeys

There is a special hotkey in RStudio for the pipe operator: Ctrl+Shift+M (Windows & Linux), Cmd+Shift+M (Mac).

Performance Considerations

While the pipe operator is useful, be aware that there is a negative impact on performance due mainly to the overhead of using it. Consider the following two things carefully when using the pipe operator:

  • Machine performance (loops)
  • Evaluation (object %>% rm() does not remove object)


Got any R Language Question?