pipeOp {base} | R Documentation |
Forward Pipe Operator
Description
Pipe a value into a call expression or a function expression.
Usage
lhs |> rhs
Arguments
lhs |
expression producing a value. |
rhs |
a call expression. |
Details
A pipe expression passes, or ‘pipes’, the result of the left-hand-side
expression lhs
to the right-hand-side expression rhs
.
The lhs
is
inserted as the first argument in the call. So x |> f(y)
is
interpreted as f(x, y)
.
To avoid ambiguities, functions in rhs
calls may not be
syntactically special, such as +
or if
.
It is also possible to use a named argument with the placeholder
_
in the rhs
call to specify where the lhs
is to
be inserted. The placeholder can only appear once on the rhs
.
The placeholder can also be used as the first argument in an
extraction call, such as _$coef
. More generally, it can be used
as the head of a chain of extractions, such as _$coef[[2]]
,
using a sequence of the extraction functions $
, [
,
[[
, or @
.
Pipe notation allows a nested sequence of calls to be written in a way that may make the sequence of processing steps easier to follow.
Currently, pipe operations are implemented as syntax transformations.
So an expression written as x |> f(y)
is parsed as f(x,
y)
. It is worth emphasizing that while the code in a pipeline is
written sequentially, regular R semantics for evaluation apply and
so piped expressions will be evaluated only when first used in the
rhs
expression.
Value
Returns the result of evaluating the transformed expression.
Background
The forward pipe operator is motivated by the pipe introduced in the magrittr package, but is more streamlined. It is similar to the pipe or pipeline operators introduced in other languages, including F#, Julia, and JavaScript.
Warning
This was introduced in R 4.1.0. Code using it will not be parsed as intended (probably with an error) in earlier versions of R.
Examples
# simple uses:
mtcars |> head() # same as head(mtcars)
mtcars |> head(2) # same as head(mtcars, 2)
mtcars |> subset(cyl == 4) |> nrow() # same as nrow(subset(mtcars, cyl == 4))
# to pass the lhs into an argument other than the first, either
# use the _ placeholder with a named argument:
mtcars |> subset(cyl == 4) |> lm(mpg ~ disp, data = _)
# or use an anonymous function:
mtcars |> subset(cyl == 4) |> (function(d) lm(mpg ~ disp, data = d))()
mtcars |> subset(cyl == 4) |> (\(d) lm(mpg ~ disp, data = d))()
# or explicitly name the argument(s) before the "one":
mtcars |> subset(cyl == 4) |> lm(formula = mpg ~ disp)
# using the placeholder as the head of an extraction chain:
mtcars |> subset(cyl == 4) |> lm(formula = mpg ~ disp) |> _$coef[[2]]
# the pipe operator is implemented as a syntax transformation:
quote(mtcars |> subset(cyl == 4) |> nrow())
# regular R evaluation semantics apply
stop() |> (function(...) {})() # stop() is not used on RHS so is not evaluated