R流水线功能

Mat*_*ews 15 pipeline r

有没有办法在R中编写流水线函数,其中一个函数的结果立即传递到下一个函数?我来自F#并且非常欣赏这种能力,但还没有找到如何在R中做到这一点.它应该很简单,但我找不到如何.在F#中它看起来像这样:

let complexFunction x =
     x |> square 
     |> add 5 
     |> toString
Run Code Online (Sandbox Code Playgroud)

在这种情况下,输入将被平方,然后添加5,然后转换为字符串.我希望能够在R中做类似的事情,但不知道如何做.我已经搜索了如何做这样的事情,但没有遇到任何问题.我想要导入数据,因为我通常必须导入它然后过滤.现在我在多个步骤中执行此操作,并且非常希望能够以F#管道方式执行某些操作.

mne*_*nel 8

这是一个使用的函数式编程方法Reduce.它实际上就是一个例子?Reduce

square <- function(x) x^2
add_5 <- function(x)  x+5
x <- 1:5
## Iterative function application:
Funcall <- function(f, ...) f(...)

Reduce(Funcall, list(as.character, add_5, square,x), right = TRUE)
## [1] "6"  "9"  "14" "21" "30"
Run Code Online (Sandbox Code Playgroud)

或者甚至更简单地使用functional包和Compose

这很好,因为它将为您创建功能

library(functional)
do_stuff <-   Compose(square,add_5,as.character )
do_stuff(1:5)
##  [1] "6"  "9"  "14" "21" "30"
Run Code Online (Sandbox Code Playgroud)

我注意到我不会认为这些方法中的任何一种都是惯用的R(如果这甚至是一个短语)


Das*_*son 7

我们可以使用Compose函数包来创建我们自己的二元运算符,它可以执行类似于您想要的操作

# 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) }
Run Code Online (Sandbox Code Playgroud)

我想我们可以在技术上做到这一点,而不需要功能包 - 但它Compose对于这项任务感觉非常正确.

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


小智 5

我想你可能只想编写一个函数来完成你想要的步骤.

complexFunction <- function(x) {
    as.character(x^2 + 5)
}
Run Code Online (Sandbox Code Playgroud)

然后打电话complexFunction(x).


编辑显示什么- [R内部做(@mnel) -的方式R解析且评估as.character(x^2 + 5)你想要做什么

您可以使用它codetools来研究R 如何将值传递给彼此

flattenAssignment(quote(as.character(x^2+5)))
[[1]]
[[1]][[1]]
x

[[1]][[2]]
`*tmp*`^2

[[1]][[3]]
`*tmp*` + 5


[[2]]
[[2]][[1]]
`as.character<-`(`*tmp*`, value = `*tmpv*`)

[[2]][[2]]
`+<-`(`*tmp*`, 5, value = `*tmpv*`)

[[2]][[3]]
`^<-`(x, 2, value = `*tmpv*`)
Run Code Online (Sandbox Code Playgroud)

或者您可以获取Lisp样式表示以查看它是如何解析的(并且结果已通过)

showTree(quote(as.character(x^2+5)))
(as.character (+ (^ x 2) 5))
Run Code Online (Sandbox Code Playgroud)