1

Using the new pipe operator |> I would like to subtract 1 from the placeholder like so:

E.g. Suppose that, within a dplyr chain inside of a mutate() I would like to create a new field mpg_minus1 that is mpg - 1.

Pretend we cannot just do mpg_minus1 = mpg - 1, this has to be part of a pipe chain.

# Error: function '-' not supported in RHS call of a pipe
mtcars |> mutate(mpg_minus1 = mpg |> `-`(1)) # vague recolection of seeing syntax like this somewhere

# Error: unexpected symbol in: "mtcars |> mutate(mpg_minus1 = mpg |> (\(.) . - 1)() mtcars"
mtcars |> mutate(mpg_minus1 = mpg |> (\(.) . - 1)())

How can I grab the placeholder and subtract 1 before moving on to next pipe operation?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

1 Answers1

4

You can "trick" the parser by wrapping the operator in parentheses:

1 |> `-`(1)
## Error: function '-' not supported in RHS call of a pipe

1 |> (`-`)(1)
## [1] 0

1 |> (\(.) . - 1)()
## [1] 0

An easy way to test how your pipes are parsed is with quote:

quote(1 |> `-`(1))
## Error: function '-' not supported in RHS call of a pipe

quote(1 |> (`-`)(1))
## (`-`)(1, 1)

quote(1 |> (\(.) . - 1)())
## (function(.) . - 1)(1)
Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48