Search code examples
rpipearithmetic-expressions

How to include binary arithmetic operators in native pipe


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?


Solution

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