代码之家  ›  专栏  ›  技术社区  ›  Alex Witsil

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

  •  1
  • Alex Witsil  · 技术社区  · 7 年前

     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 回复  |  直到 7 年前
        1
  •  2
  •   Kamil Bartoń    7 年前

    以你为例,, ... 接下来是什么 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
  •  1
  •   jay.sf    7 年前

    x 两个函数中的s不相同。

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

    你看,如果你不通过辩论 FUN(x) fun1() 不认识这个人 x=10 .

        3
  •  0
  •   Alex Witsil    7 年前

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

    然后运行fun2作为:

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

    推荐文章