让我们评估环境中的表达式:
> 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()
。
答案 0 :(得分:2)
当您执行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"