嵌套函数环境选择 [英] Nested function environment selection
问题描述
我正在编写一些用于执行重复任务的函数,但是我试图将加载数据的时间减至最少.基本上,我有一个函数可以获取一些信息并进行绘制.然后,我有了第二个函数,该函数将循环遍历并将多个图输出到.pdf.在这两个函数中,我都有以下代码行:
I am writing some functions for doing repeated tasks, but I am trying to minimize the amount of times I load the data. Basically I have one function that takes some information and makes a plot. Then I have a second function that will loop through and output multiple plots to a .pdf. In both functions I have the following line of code:
if(load.dat) load("myworkspace.RData")
其中load.dat
是逻辑,我需要的数据存储在myworkspace.RData中.当我调用循环并输出多个图的包装函数时,我不想在每次对内部函数的调用中重新加载工作区.我以为我只需要在包装函数中加载一次工作区,然后内部函数就可以访问该数据,但是我却指出了错误.
where load.dat
is a logical and the data I need is stored in myworkspace.RData. When I am calling the wrapper function that loops through and outputs multiple plots I do not want to reload the workspace in every call to the inner function. I thought I could just load the workspace once in the wrapper function, then the inner function could access that data, but I got an error stating otherwise.
所以我的理解是,当一个函数在其本地环境中找不到该变量时(该函数在调用该函数时创建),该函数将在父环境中查找该变量.
So my understanding was when a function cannot find the variable in its local environment (created when the function gets called), the function will look to the parent environment for the variable.
我假设内部函数调用的父环境将是外部函数调用.显然这是不正确的:
I assumed the parent environment to the inner function call would be the outer function call. Obviously this is not true:
func1 <- function(...){
print(var1)
}
func2 <- function(...){
var1 <- "hello"
func1(...)
}
> func2()
Error in print(var1) : object 'var1' not found
在阅读了许多问题之后,使用了语言手册和此确实很有帮助的博客文章,我提出了以下建议:
After reading numerous questions, the language manual, and this really helpful blog post, I came up with the following:
var1 <- "hello"
save(list="var1",file="test.RData")
rm(var1)
func3 <- function(...){
attach("test.RData")
func1(...)
detach("file:test.RData")
}
> func3()
[1] "hello"
是否有更好的方法可以做到这一点?当func2
调用func1
时,为什么func1
在由func2
创建的本地环境中不查找未定义的变量?
Is there a better way to do this? Why doesn't func1
look for undefined variables in the local environment created by func2
, when it was func2
that called func1
?
注意:我不知道如何命名这个问题.如果有人有更好的建议,我将对其进行更改并进行编辑.
Note: I did not know how to name this question. If anyone has better suggestions I will change it and edit this line out.
推荐答案
要说明词汇作用域,请考虑以下内容:
To illustrate lexical scoping, consider the following:
首先,我们创建一个沙箱环境,只是为了避免常见的R_GlobalEnv:
First let's create a sandbox environment, only to avoid the oh-so-common R_GlobalEnv:
sandbox <-new.env()
现在,我们在其中添加了两个函数:f
,用于查找名为x
的变量;和g
,它定义了本地x
并调用f
:
Now we put two functions inside it: f
, which looks for a variable named x
; and g
, which defines a local x
and calls f
:
sandbox$f <- function()
{
value <- if(exists("x")) x else "not found."
cat("This is function f looking for symbol x:", value, "\n")
}
sandbox$g <- function()
{
x <- 123
cat("This is function g. ")
f()
}
技术性:在控制台中输入功能定义会导致将封闭环境设置为R_GlobalEnv
,因此我们手动强制f
和g
的机柜匹配它们所属"的环境:>
Technicality: entering function definitions in the console causes then to have the enclosing environment set to R_GlobalEnv
, so we manually force the enclosures of f
and g
to match the environment where they "belong":
environment(sandbox$f) <- sandbox
environment(sandbox$g) <- sandbox
呼叫g
. f
找不到本地变量x=123
:
Calling g
. The local variable x=123
is not found by f
:
> sandbox$g()
This is function g. This is function f looking for symbol x: not found.
现在,我们在全局环境中创建一个x
并调用g
.函数f
首先在沙箱中查找x
,然后在沙箱的父项中查找,恰好是R_GlobalEnv:
Now we create a x
in the global environment and call g
. The function f
will look for x
first in sandbox, and then in the parent of sandbox, which happens to be R_GlobalEnv:
> x <- 456
> sandbox$g()
This is function g. This is function f looking for symbol x: 456
只需检查f
首先在其外壳中查找x
,我们就可以在其中放置x
并调用g
:
Just to check that f
looks for x
first in its enclosure, we can put a x
there and call g
:
> sandbox$x <- 789
> sandbox$g()
This is function g. This is function f looking for symbol x: 789
结论:R中的符号查找遵循封闭环境链,而不是执行嵌套函数调用期间创建的评估框架.
Conclusion: symbol lookup in R follows the chain of enclosing environments, not the evaluation frames created during execution of nested function calls.
Just adding a link to this very interesting answer from Martin Morgan on the related subject of parent.frame()
vs parent.env()
这篇关于嵌套函数环境选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!