R中的parent.frame()和parent.env()有什么区别?它们在通过引用进行调用方面有何不同? [英] What is the difference between parent.frame() and parent.env() in R; how do they differ in call by reference?
问题描述
如果有人可以用一个简单的例子来说明这一点,那会有所帮助吗?
It would be helpful if someone can illustrate this with a simple example?
此外,在什么地方使用parent.frame()
代替parent.env()
有用,反之亦然.
Also, where would it be useful to use parent.frame()
instead of parent.env()
and vice versa.
推荐答案
parent.env
是定义闭包(例如函数)的环境. parent.frame
是从中调用闭包的环境.
parent.env
is the environment in which a closure (e.g., function) is defined. parent.frame
is the environment from which the closure was invoked.
f = function()
c(f=environment(), defined_in=parent.env(environment()),
called_from=parent.frame())
g = function()
c(g=environment(), f())
然后
> g()
$g
<environment: 0x14060e8>
$f
<environment: 0x1405f28>
$defined_in
<environment: R_GlobalEnv>
$called_from
<environment: 0x14060e8>
我不确定何时只有凡人会真正使用它们,但是这里的概念对于理解词法范围很有用
I'm not sure when a mere mortal would ever really want to use them, but the concepts are useful in understanding lexical scope here
> f = function() x
> g = function() { x = 2; f() }
> h = function() { x = 3; function() x }
> x = 1
> f()
[1] 1
> g()
[1] 1
> h()()
[1] 3
或在R简介中的神秘银行帐户"示例中.?parent.frame
详细信息"部分的第一段可能会阐明情况.
or in the enigmatic 'bank account' example in the Introduction to R. The first paragraph of the Details section of ?parent.frame
might clarify things.
环境在R中无处不在,例如search()
路径是(近似)以同级->父级关系链接在一起的环境.有时会看到env = new.env(parent=emptyenv())
绕过符号查找-通常env[["x"]]
首先会在env
中查找,然后在env
的父级中查找(如果找不到).同样,<<-
查找从parent.env
开始的分配. R中相对较新的引用类实现依靠这些思想来定义一个特定于实例的环境,在该环境中可以找到符号(实例字段和方法).
Environments are pervasive in R, e.g., the search()
path is (approximately) environments chained together in a sibling -> parent relationship. One sometimes sees env = new.env(parent=emptyenv())
to circumvent symbol look-up -- normally env[["x"]]
would look first in env
, and then in env
's parent if not found. Likewise, <<-
looks for assignment starting in the parent.env
. The relatively new reference class implementation in R relies on these ideas to define an instance-specific environment in which symbols (instance fields and methods) can be found.
这篇关于R中的parent.frame()和parent.env()有什么区别?它们在通过引用进行调用方面有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!