R进行“评估”时,R在哪里寻找对象



让我们在环境中评估表达式:

> myenv <- new.env()
> assign("x", 2, myenv)
> f <- function(x) x+1
> eval(expression(f(x)), myenv)
[1] 3

我不明白为什么它有效,因为f不在myenv中。R如何找到f

让我们看一下帮助:

Usage
eval(expr, envir = parent.frame(),
           enclos = if(is.list(envir) || is.pairlist(envir))
                       parent.frame() else baseenv())
Arguments
envir   
the environment in which expr is to be evaluated. May also be NULL, a list, a data frame, a pairlist or an integer as specified to sys.call.
enclos  
Relevant when envir is a (pair)list or a data frame. Specifies the enclosure, i.e., where R looks for objects not found in envir. This can be NULL (interpreted as the base package environment, baseenv()) or an environment.

因此,它说r也在enclos中,即baseenv()。但是f不在baseenv()中。

进行myenv <- new.env()时,默认情况下,它将新环境的父环境设置为当前环境。签名是

new.env(hash = TRUE, parent = parent.frame(), size = 29L)

因此,如果在您执行表达式的环境中未解决符号名称,则R将检查父环境的链。您可以通过将空环境指定为父环境来禁用该行为。

myenv <- new.env(parent=emptyenv())
assign("x", 2, myenv)
f <- function(x) x+1
eval(expression(f(x)), myenv)
# Error in f(x) : could not find function "f"

最新更新