【问题标题】:eval in R behaviorR行为中的评估
【发布时间】:2021-07-28 08:47:58
【问题描述】:

我正在尝试了解函数内部的 eval 函数行为,因此假设这是我的设置:

定义了两个全局变量 x 和 a

x <- 'a'
a <- 'c'

然后用三个打印语句定义了一个函数 f,我对 eval、envir 参数默认为 parent.frame() 的事实感到困惑,但是,如果我故意说出来,结果会有所不同。为什么?

下面是与cmets一起理解的代码,非常感谢cmets提前解决这个问题。

f <- function(x){
  ## 1st statement, I get it that evaluation should be done in current environment 
  print(eval(quote(x), envir = environment()))
  
  
  ## 2nd statement, This I don't get, as the default is parent.frame(), shouldn't it be 
  ## evaluated in the calling scope of function which is global environment. As per 
  ## documentation parent.frame() is the default then why this result evaluates to current
  ## environment, whereas the last print statement when specifically mentions parent.frame gives a different result entirely.
  ## Note the documentation says: If envir is not specified, then the default is parent.frame() (the environment where the call to eval was made).
  ## So, my understanding of parent.frame is that it is that frame where calls are happening(basically calling environment), Am I mistaken here?
  print(eval(quote(x)))
  
  ## 3rd , This behaviour seems okay as parent.frame is referencing the calling scope which is global
  print(eval(quote(x), envir=parent.frame()))
}

输出:

#> f(a)
#[1] "c"
#[1] "c"
#[1] "a"

【问题讨论】:

    标签: r eval


    【解决方案1】:

    提供的参数和默认参数的范围不同。

    提供的参数在调用者的评估框架中进行评估,即您的示例中的f。因此,envir 设置为该调用的parent.frame,即全局环境。

    默认参数在定义它们的函数的评估框架中进行评估,在您的示例中为eval。在eval()调用中,父框架是f的评估框架。

    如果您仔细考虑一下,这很有意义。作为f() 的作者,您应该知道在评估它时哪些变量是可见的,所以这些是用于评估参数表达式的变量。另一方面,eval() 的作者不知道它的调用者可以使用什么,因此必须在其自己的评估框架中评估默认参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 2016-08-19
      • 2021-07-07
      • 2015-10-19
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多