在R中绑定外部变量 [英] Binding outside variables in R
问题描述
假设我有以下函数:
pre $ code g = function(x)x + h
现在,如果我在我的环境中有一个名为 h
的对象,我会没有任何问题:
h = 4
g(2)
##应该是6
现在,我有另一个功能:
f = function(){
h = 3
g(2)
}
我预计:
rm(h)
f()
##应该是5,不是吗?
相反,我得到一个错误
<$ p (2):找不到对象'h'
我希望在 f
的环境中评估 g
,这样 h
in f
将被绑定到g中,就像我执行 g $ c时一样$ c>在
.GlobalEnv
中。这不会发生(显然)。任何解释为什么?如何克服这个问题,以便函数中的函数(例如 g
)将使用封闭环境进行评估?
函数的封闭环境和它的(父级)评估框架 不同。 封闭环境在函数定义时设置。如果您在R提示符处定义您的函数 然后封闭环境 家长评估框架是 如果您希望 现在 或者,您可以修改<$ c Suppose I have the following function: Now, if I have in my environment an object named Now, I have another function: I would expect: Instead, I get an error I would expect There's a difference between the enclosing environment of a function, and its (parent) evaluation frame. The enclosing environment is set when the function is defined. If you define your function then the enclosing environment of the parent evaluation frame is If you want Now Alternatively, you can modify the enclosing environment of
这篇关于在R中绑定外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b g
:
g =函数(x)x + h
g
将成为全球环境。现在,如果您从另一个函数调用
g
:
$ b
f = function ){
h = 3
g(2)
}
f
的环境。但是这并不会改变 g
的封闭环境,这是一个固定的属性,不依赖于它的评估位置。这就是为什么它不会取得 f
中定义的 h
的值。
g
使用<$ c中定义的 h
的值$ c> f ,那么你还应该在 f
中定义 g
:
f = function(){
h = 3
g = function(x)x + h
g 2)
}
g
的封闭环境将是 f
的环境(但请注意,这个 g
不等于 g
您之前在R提示符处创建的)。
f = function(){
h = 3 $ c $ g $ / code>
environment(g)< - environment()
g(2)
}
g = function(x) x+h
h
, I would not have any problem:h = 4
g(2)
## should be 6
f = function() {
h = 3
g(2)
}
rm(h)
f()
## should be 5, isn't it?
## Error in g(2) : object 'h' not found
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?g
at the R prompt:g = function(x) x+h
g
will be the global environment. Now if you call g
from another function:f = function() {
h = 3
g(2)
}
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
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
'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
as follows:f = function() {
h = 3
environment(g) <- environment()
g(2)
}