如何在R中实现F#的前向管道运算符? [英] how to implement F#'s forward pipe operator in R?

查看:70
本文介绍了如何在R中实现F#的前向管道运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在R中实现F#的前向管道运算符?操作员可以轻松地链接一系列计算.例如,当您有输入data并想依次调用函数foobar时,可以编写:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆