如何在 R 中实现 F# 的前向管道运算符? [英] how to implement F#'s forward pipe operator in R?
问题描述
如何在 R 中实现 F# 的前向管道运算符?运算符可以轻松链接一系列计算.例如,当你有一个输入data
,想依次调用foo
和bar
函数,你可以这样写:
How can you implement F#'s forward pipe operator in R? The operator makes it possible to easily chain a sequence of calculations. For example, when you have an input data
and want to call functions foo
and bar
in sequence, you can write:
data |> foo |> bar
而不是写bar(foo(data))
.好处是您可以避免使用括号,并且计算的编写顺序与它们的执行顺序相同(从左到右).在 F# 中,运算符定义如下:
Instead of writing bar(foo(data))
. The benefits are that you avoid some parentheses and the computations are written in the same order in which they are executed (left-to-right). In F#, the operator is defined as follows:
let (|>) a f = f a
看起来 %...% 可以用于二元运算符,但这如何工作?
It would appear that %...% can be used for binary operators, but how would this work?
推荐答案
我不知道它在任何实际用途中的表现如何,但这似乎 (?)参数函数...
I don't know how well it would hold up to any real use, but this seems (?) to do what you want, at least for single-argument functions ...
> "%>%" <- function(x,f) do.call(f,list(x))
> pi %>% sin
[1] 1.224606e-16
> pi %>% sin %>% cos
[1] 1
> cos(sin(pi))
[1] 1
就其价值而言,截至目前(2021 年 12 月 3 日),除了 magrittr
/tidyverse 管道(%>%
)之外,还有一个原生的R 中的管道 |>
(以及可以在开发版本中启用的实验 =>
运算符):参见 此处.
For what it's worth, as of now (3 December 2021), in addition to the magrittr
/tidyverse pipe (%>%
), there also a native pipe |>
in R (and an experimental =>
operator that can be enabled in the development version): see here, for example.
这篇关于如何在 R 中实现 F# 的前向管道运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!