1

I am trying to integrate binary arithmetic operators in the native pipe.

Reproducible example:

# without pipe
round(sample(1:2, 1) / 3, 2)
## [1] 0.33

# with pipe
1:2 |> sample(1) / 3 |> round(2)
## [1] 0.3333333 # round is ignored
1:2 |> (sample(1) / 3) |> round(2)
## Error: function '(' not supported in RHS call of a pipe
1:2 |> sample(1) |> '/'(3) |> round(2)
## Error: function '/' not supported in RHS call of a pipe

How can I achieve the same result with a pipe?

vonjd
  • 4,202
  • 3
  • 44
  • 68

2 Answers2

2

There are several ways to do this:

library(tidyverse)

# use aliases of the magrittr package
1:2 |> sample() |> divide_by(3) |> round(3)

# use map to apply a function to each element
1:2 |> sample() |> map_dbl(~ .x / 3) |> round(3)

# calling the operator as a function using backticks
1:2 |> sample() |> (`/`)(3) |> round(3)

danlooo
  • 10,067
  • 2
  • 8
  • 22
1

The new native pipe does have a (imho) strange behaviour. You could use an anonymous function:

1:2  |>  {\(x) sample(x, 1) / 3}() |>  round(2)
#> [1] 0.33

Take a look at this question: What are the differences between R's new native pipe `|>` and the magrittr pipe `%>%`?

Martin Gal
  • 16,640
  • 5
  • 21
  • 39