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

Passing the same argument to multiple 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 但我特别希望将 same 参数传递给多个嵌套函数。

两个函数中的x不一样。

考虑一下:

fun1 <- function(y) y^2 
fun2 <- function(x,FUN) x + FUN(x) 

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

你看,如果你不通过 FUN(x) 传递参数,fun1() 将无法识别 x=10

在您的示例中,...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
 }

与 Kamil 相比,另一个不太稳健但可能更简单的解决方案是依赖定义函数的参数顺序:

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

然后 运行 fun2 为:

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

这又依赖于了解函数参数的顺序,这有点危险。