pipeOp: Forward Pipe Operator

pipeOpR 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 or an expression of the form symbol => call.

Details

A pipe expression passes, or pipes, the result of the left-hand side expression lhs to the right-hand side expression rhs.

If the rhs expression is a call, then 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.

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.

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))

# passing the lhs into an argument other than the first:
mtcars |> subset(cyl == 4) |> (function(d) lm(mpg ~ disp, data = d))()

# 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