【问题标题】:When returning a function with a passed parameter, how does the parameter get stored?返回带有传递参数的函数时,参数如何存储?
【发布时间】:2017-07-13 16:08:45
【问题描述】:

以下是将参数传递给返回函数的人为示例。我想让返回的函数将参数评估为 2,事实上,这就是它的作用!

但是,这是如何工作的?当我打印该函数时,它显示“param”而不是“2”。但是当我debug() 时,我确认 param 实际上是 2。

f <- function(x, param = 2) {      
  my_cdf <- ecdf(x)      
  function(new_x) {
      my_cdf(new_x) * param
  }
}

g <- f(1:10)
g

# > function(new_x) {
# >   my_cdf(new_x) * param
# > }

【问题讨论】:

    标签: r


    【解决方案1】:

    由于param 没有在使用它的函数中定义,param 在环境中查找,其中使用它的函数定义 并且 param = 2环境。这称为词法作用域。

    如果您想将param 实际替换到函数中,请尝试substitute,如下所示:

    f <- function(x, param = 2) {      
      my_cdf <- ecdf(x)   
      F <- function(new, x)
          my_cdf(new_x) * param
      body(F) <- do.call("substitute", list(body(F), list(param = param)))
      F
    }
    f(1:10)
    

    【讨论】:

    • 我通过显示返回的函数对我的问题进行了更正,但您的回答仍然适用。我最初试图让 $param$ 被评估,以便在检查 $g$ 时,它会显示 2。既然一切正常,现在就更没有实际意义了。
    • 好的。添加了一个实际替换 param 的示例。
    【解决方案2】:

    来自 Advanced R 的 chapter 对正在发生的事情有更详细的说明。

    那一章的几个例子:

    as.list(environment(g))
    
    # $my_cdf
    # Empirical CDF 
    # Call: ecdf(x)
    #  x[1:10] =      1,      2,      3,  ...,      9,     10
    # 
    # $x
    #  [1]  1  2  3  4  5  6  7  8  9 10
    # 
    # $param
    # [1] 2
    
    library(pryr)
    unenclose(g)
    
    # function (new_x) 
    # {
    #     (function (v) 
    #     .approxfun(x, y, v, method, yleft, yright, f))(new_x) * 2
    # }
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 2014-09-03
      • 2015-08-29
      • 2010-11-20
      相关资源
      最近更新 更多