R流水线功能 [英] R Pipelining functions

查看:85
本文介绍了R流水线功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在R中编写流水线函数,其中一个函数的结果立即传递到下一个?我来自F#,真的很喜欢这种功能,但是还没有找到如何在R中做到这一点.它应该很简单,但是我找不到如何做.在F#中,它看起来像这样:

Is there a way to write pipelined functions in R where the result of one function passes immediately into the next? I'm coming from F# and really appreciated this ability but have not found how to do it in R. It should be simple but I can't find how. In F# it would look something like this:

let complexFunction x =
     x |> square 
     |> add 5 
     |> toString

在这种情况下,输入将被平方,然后添加5,然后转换为字符串.我希望能够在R中做类似的事情,但不知道如何做.我一直在寻找如何做这样的事情,但没有遇到任何问题.我要用它来导入数据,因为通常我必须先将其导入然后进行过滤.现在,我分多个步骤执行此操作,并且确实希望能够像在F#中使用管道一样执行某些操作.

In this case the input would be squared, then have 5 added to it and then converted to a string. I'm wanting to be able to do something similar in R but don't know how. I've searched for how to do something like this but have not come across anything. I'm wanting this for importing data because I typically have to import it and then filter. Right now I do this in multiple steps and would really like to be able to do something the way you would in F# with pipelines.

推荐答案

我们可以使用功能包中的Compose来创建自己的二进制运算符,以执行与所需操作类似的操作

We can use Compose from the functional package to create our own binary operator that does something similar to what you want

# Define our helper functions
square <- function(x){x^2}
add5 <- function(x){x + 5}

# functional contains Compose
library(functional)

# Define our binary operator
"%|>%" <- Compose

# Create our complexFunction by 'piping' our functions
complexFunction <- square %|>% add5 %|>% as.character
complexFunction(1:5)
#[1] "6"  "9"  "14" "21" "30"


# previously had this until flodel pointed out
# that the above was sufficient
#"%|>%" <- function(fun1, fun2){ Compose(fun1, fun2) }

我想我们可以在不需要功能包的情况下从技术上做到这一点-但使用Compose进行此任务感觉很正确.

I guess we could technically do this without requiring the functional package - but it feels so right using Compose for this task.

"%|>%" <- function(fun1, fun2){
    function(x){fun2(fun1(x))}
}
complexFunction <- square %|>% add5 %|>% as.character
complexFunction(1:5)
#[1] "6"  "9"  "14" "21" "30"

这篇关于R流水线功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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