Skip to contents

%->% convey operator allows omission of the %>% pipe operator in its environment as well as setting local bindings that can be used at later stages of the sequence of functions.

Usage

obj %->% code

Arguments

obj

[R object] Any object, specifically data or results of previous pipes.

code

[individual bindings and R commands] Instructions wrapped in curly braces to encapsualte the context of the pipe.

Value

An object resulting from the transformations applied to it by the code.

Writing Shorter, More Integrated Pipes

Piping is usually one single context, therefore all the extra pipe operators at the end of each instruction seems extraneous. Nevertheless, one may need to record the result of a pipe up to a certain stage, to later build the whole object out of the simpler modifications of the original object. This too is Something that the simple pipe operator can't handle. Therefore, the solution is to define a context for these two cases, perform the operations therein, and return the desired result. That is what the "convey" operator does.

Usage of the convey Operator

object %->% code

The object part can be any single object or the result of previous piping operations. The instructions are exactly as if each command was sequentially passed to the next via the conventional magrittr pipe. Each time a function instruction is followed by a binding, the respective symbol is bound to the specified computation. See examples and conserve.

See also

Other result assemblers: %$>%(), %<-%(), %to%(), conserve(), control()

Examples

# use piping context instead of sequentially using the `magrittr` pipe:
testdf <- tibble::tribble(
  ~x, ~y,
  1, 2,
  5, 9,
  12, 8
)
mydf <- testdf %->% {
  dplyr::mutate(x2 = x^2)
  dplyr::mutate(x6 = x2^3)
}
all.equal(
  mydf,
  testdf %>% dplyr::mutate(x2 = x^2) %>% dplyr::mutate(x6 = x2^3)
)
#> [1] TRUE


# bind intermediate values for later use
mydf2 <- testdf %->% {
  dplyr::mutate(x2 = x^2)
  somedf <- .
  dplyr::mutate(x6 = (somedf$x2)^3)
}
all.equal(mydf, mydf2)
#> [1] TRUE
## intermediate values do not remain after the pipe is done
as.character(tryCatch(somedf, error = function(e) e))
#> [1] "Error in doTryCatch(return(expr), name, parentenv, handler): object 'somedf' not found\n"

# automatic data masking in assignment
mydf <- testdf %->% {
  dplyr::mutate(x2 = x^2)
  colx2xy <- x2 + x + y
  dplyr::mutate(x2xyval = colx2xy)
  dplyr::mutate(x2xy = x2 + x + y)
}
all.equal(mydf$x2xyval, mydf$x2xy)
#> [1] TRUE