I was playing around with R and noticed some inconsistencies with the Global Environment surrounding function calls differing from the actual global environment.
我在玩R,注意到与函数调用相关的全局环境不一致,与实际的全局环境不同。
Consider the following:
考虑以下:
> test = function ()
+ {
+ print(environmentName(as.environment(-1)))
+ print(ls(as.environment(-1)))
+ print(environmentName(.GlobalEnv))
+ print(ls(.GlobalEnv))
+ as.environment(-1)
+ }
> foo = 1
> ls()
[1] "foo" "test"
> test()
[1] ""
[1] "doTryCatch" "expr" "handler" "name" "parentenv"
[1] "R_GlobalEnv"
[1] "foo" "test"
<environment: R_GlobalEnv>
Within the function call, as.environment(-1)
returns an environment that claims it is <environment: R_GlobalEnv>
but when calling environmentName
on said environment, its name is an empty character. Furthermore, the contents of it differ from what is in the true global environment. What exactly is going on here?
在函数调用中,as.environment(-1)返回一个声明它是 <环境:r_globalenv> 的环境,但是在该环境中调用环境名时,它的名称是一个空字符。此外,它的内容不同于真正的全局环境。这里到底发生了什么?
I first noticed the error using mget
within a call, as a variable defined globally could not be found. This seems counter-intuitive because normally when referencing a variable within a function, R will search upwards in the enclosing environments until it finds a definition for a variable, including the global environment.
我首先注意到调用中使用mget的错误,因为无法找到全局定义的变量。这似乎与直觉相反,因为通常当在函数中引用一个变量时,R会在封闭的环境中向上搜索,直到找到一个变量的定义,包括全局环境。
1 个解决方案
#1
4
This is a consequence of lazy evaluation:
这是懒惰评估的结果:
test <- function () {
e <- as.environment(-1)
list(
lazy = ls(as.environment(-1)),
eager = ls(envir = e)
)
}
foo <- 1
test()
#> $lazy
#> [1] "doTryCatch" "expr" "handler" "name" "parentenv"
#>
#> $eager
#> [1] "foo" "test"
#1
4
This is a consequence of lazy evaluation:
这是懒惰评估的结果:
test <- function () {
e <- as.environment(-1)
list(
lazy = ls(as.environment(-1)),
eager = ls(envir = e)
)
}
foo <- 1
test()
#> $lazy
#> [1] "doTryCatch" "expr" "handler" "name" "parentenv"
#>
#> $eager
#> [1] "foo" "test"