问题描述
假设我有以下功能:
g = function(x) x+h
现在,如果我的环境中有一个名为 h
的对象,我就不会有任何问题:
Now, if I have in my environment an object named h
, I would not have any problem:
h = 4
g(2)
## should be 6
现在,我有另一个功能:
Now, I have another function:
f = function() {
h = 3
g(2)
}
我希望:
rm(h)
f()
## should be 5, isn't it?
相反,我收到一个错误
## Error in g(2) : object 'h' not found
我希望 g
在 f
的环境中被评估,这样 f
中的 h
将绑定到 g 中的 h,就像我在 .GlobalEnv
中执行 g
时一样.这不会发生(显然).任何解释为什么?如何克服这个问题,以便使用封闭环境评估函数内的函数(例如 g
)?
I would expect g
to be evaluated within the environment of f
, so that the h
in f
will be bound to the h in g, as it was when I executed g
within the .GlobalEnv
. This does not happen (obviously). any explanation why? how to overcome this so that the function within the function(e.g. g
) will be evaluated using the enclosing environment?
推荐答案
函数的封闭环境与其(父)评估框架之间存在差异.
There's a difference between the enclosing environment of a function, and its (parent) evaluation frame.
在定义函数时设置封闭环境.如果在 R 提示符下定义函数 g
:
The enclosing environment is set when the function is defined. If you define your function g
at the R prompt:
g = function(x) x+h
那么g
的封闭环境就是全局环境.现在,如果你从另一个函数调用 g
:
then the enclosing environment of g
will be the global environment. Now if you call g
from another function:
f = function() {
h = 3
g(2)
}
父评估框架是 f
的环境.但这不会改变 g
的封闭环境,这是一个固定的属性,不依赖于它的评估位置.这就是为什么它不会获取 f
中定义的 h
的值.
the parent evaluation frame is f
's environment. But this doesn't change g
's enclosing environment, which is a fixed attribute that doesn't depend on where it's evaluated. This is why it won't pick up the value of h
that's defined within f
.
如果你想让 g
使用 f
中定义的 h
的值,那么你还应该定义 g
> 在 f
内:
If you want g
to use the value of h
defined within f
, then you should also define g
within f
:
f = function() {
h = 3
g = function(x) x+h
g(2)
}
现在 g
的封闭环境将是 f
的环境(但要注意,这个 g
与 g
不同code>g 您之前在 R 提示符下创建的).
Now g
's enclosing environment will be f
's environment (but be aware, this g
is not the same as the g
you created earlier at the R prompt).
或者,您可以修改g
的封闭环境如下:
Alternatively, you can modify the enclosing environment of g
as follows:
f = function() {
h = 3
environment(g) <- environment()
g(2)
}
这篇关于在 R 中绑定外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!