我正在尝试将二进制算术运算符集成到本机管道中。
可重现的例子:
# 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)