如何在本机管道中包含二进制算术运算符
How to include binary arithmetic operators in native pipe
我正在尝试在本机管道中集成二进制算术运算符。
可重现的例子:
# 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
如何使用管道获得相同的结果?
有几种方法可以做到这一点:
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)
新的本地管道确实有一个(恕我直言)奇怪的行为。您可以使用匿名函数:
1:2 |> {\(x) sample(x, 1) / 3}() |> round(2)
#> [1] 0.33
看看这个问题:What are the differences between R's new native pipe `|>` and the magrittr pipe `%>%`?
我正在尝试在本机管道中集成二进制算术运算符。
可重现的例子:
# 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
如何使用管道获得相同的结果?
有几种方法可以做到这一点:
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)
新的本地管道确实有一个(恕我直言)奇怪的行为。您可以使用匿名函数:
1:2 |> {\(x) sample(x, 1) / 3}() |> round(2)
#> [1] 0.33
看看这个问题:What are the differences between R's new native pipe `|>` and the magrittr pipe `%>%`?