如何在R中实现F#的前向管道运算符? [英] how to implement F#'s forward pipe operator in R?
问题描述
如何在R中实现F#的前向管道运算符?操作员可以轻松地链接一系列计算.例如,当您有输入data
并想依次调用函数foo
和bar
时,可以编写:
data |> foo |> bar
代替编写bar(foo(data))
.这样做的好处是,您可以避免使用括号,并以与执行相同的顺序(从左到右)来编写计算.在F#中,运算符的定义如下:
let (|>) a f = f a
%...%似乎可以用于二进制运算符,但是这如何工作?
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
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
这篇关于如何在R中实现F#的前向管道运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!