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.
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 }
lhs | rhs |
---|---|
A value or the magrittr placeholder. | A function call using the magrittr semantics |
%>%
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.
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
).
There is a special hotkey in RStudio for the pipe operator: Ctrl+Shift+M
(Windows & Linux), Cmd+Shift+M
(Mac).
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:
object %>% rm()
does not remove object
)