Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Also, where would it be useful to use parent.frame() instead of parent.env() and vice versa.

like image 281
suncoolsu Avatar asked Sep 16 '11 01:09

suncoolsu


People also ask

What is parent frame in R?

The parent frame of a function evaluation is the environment in which the function was called. It is not necessarily numbered one less than the frame number of the current evaluation, nor is it the environment within which the function was defined.

What does global environment mean in R?

When a user starts a new session in R, the R system creates a new environment for objects created during that session. This environment is called the global environment. The global environment is not actually the root of the tree of environments.

How to create new environment in R studio?

These functions create new environments. env() creates a child of the current environment by default and takes a variable number of named objects to populate it. new_environment() creates a child of the empty environment by default and takes a named list of objects to populate it.


1 Answers

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()) 

and then

> 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 

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.

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.

like image 155
Martin Morgan Avatar answered Sep 28 '22 23:09

Martin Morgan