将相同的参数传递给多个嵌套函数

时间:2018-11-24 22:07:43

标签: r function arguments nested-function

我想将相同的参数传递给几个嵌套函数。例如,给定2个功能:

 fun1 = function(x){x^2}
 fun2 = function(x,FUN,...) { x + FUN(...) }

我想实现这样的东西:

 fun2(x=10,FUN=fun1)  ## this returns error

在此示例中,我想获得的输出为 10 + 10 ^ 2 = 110

我看到了以下已回答的问题:Passing arbitrary arguments to multiple nested functions in R,但我特别希望将相同参数传递给多个嵌套函数。

3 个答案:

答案 0 :(得分:2)

在您的示例中,...FUN参数之后的内容,即为空。您可以使用sys.call来重用参数,例如:

 fun2 <- function(FUN, x, ...) {
     cl <- match.call(expand.dots = TRUE) # unevaluated expression `fun2(x=10,FUN=fun1)`
# Note: sys.call would work only if the arguments were named
     cl[[1]] <- cl$FUN # substitute `fun2`. Now cl is `fun1(x=10,FUN=fun1)`
     cl$FUN <- NULL # remove FUN argument. Now cl is `fun1(x=10)`
     result.of.FUN <- eval.parent(cl) # evaluate the modified expression
     x + result.of.FUN
 }

答案 1 :(得分:1)

两个功能中的const MyStub = { template: '<div />', methods: { someMethod() {} } } mount(TestComponent, { stubs: { 'my-stub': MyStub } }) 不同。

考虑一下:

x

您看到,如果不使用fun1 <- function(y) y^2 fun2 <- function(x,FUN) x + FUN(x) > fun2(x=10, FUN=fun1) [1] 110 传递参数,则FUN(x)无法识别fun1()

答案 2 :(得分:0)

与Kamil相比,另一种较不健壮但也许更简单的解决方案是依赖于这样定义的函数的参数顺序:

fun1 = function(x){x^2}
fun2 = function(x,FUN,...) { x + FUN(...) }

然后将fun2运行为:

 > fun2(x=10,FUN=fun1,10)
 [1] 110 

这再次依赖于了解函数参数的顺序,这有些危险。