R 将同一参数传递给多个嵌套函数
我想将相同的参数传递给几个嵌套函数。例如,给定2个函数:R 将同一参数传递给多个嵌套函数,r,function,arguments,nested-function,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的输出 我已经看到了这个问题的答案:但我特别希望将相同的参数传递给多个嵌套函数 两种功能中的xs不相同 考虑这一点: fun1 <- func
fun1 = function(x){x^2}
fun2 = function(x,FUN,...) { x + FUN(...) }
我想实现如下内容:
fun2(x=10,FUN=fun1) ## this returns error
在本例中,我希望得到10+10^2=110的输出
我已经看到了这个问题的答案:但我特别希望将相同的参数传递给多个嵌套函数 两种功能中的
x
s不相同
考虑这一点:
fun1 <- function(y) y^2
fun2 <- function(x,FUN) x + FUN(x)
> fun2(x=10, FUN=fun1)
[1] 110
fun1在您的示例中,..
是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
}
fun2与Kamil的解决方案相比,另一个不太可靠但可能更简单的解决方案是依赖定义函数的参数顺序:
fun1 = function(x){x^2}
fun2 = function(x,FUN,...) { x + FUN(...) }
然后运行fun2作为:
> fun2(x=10,FUN=fun1,10)
[1] 110
这同样依赖于知道函数参数的顺序,这有点危险 可以肯定的是,为什么不使用工厂函数呢?(见)我喜欢你在这里做的事情,但有两点意见。(i) 用x定义fun1(即fun1