【问题标题】:Passing the same argument to multiple nested function将相同的参数传递给多个嵌套函数
【发布时间】:2018-11-24 22:07:42
【问题描述】:

我想将相同的参数传递给几个嵌套函数。例如,给定 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 参数传递给多个嵌套函数。

【问题讨论】:

标签: r function arguments nested-function


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    xs 在两个函数中并不相同。

    考虑一下:

    fun1 <- function(y) y^2 
    fun2 <- function(x,FUN) x + FUN(x) 
    
    > fun2(x=10, FUN=fun1)
    [1] 110
    

    你看,如果你不使用FUN(x) 传递参数,fun1() 就无法识别x=10

    【讨论】:

    • 我喜欢你在这里所做的,但有 2 个 cmets。 (i) 根据 x 定义 fun1 (即 fun1
    【解决方案3】:

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

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

    然后运行 ​​fun2 为:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多