Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is parent frame of R

Tags:

r

What is parent frame of R. By the way way, what does parent frame mean? I guess it's the defining environment instead of calling environment since R uses lexical scoping, but I am not sure. Thanks.

like image 640
eifphysics Avatar asked Feb 21 '15 02:02

eifphysics


People also ask

What is R environment type?

R Programming Environment Environment can be thought of as a collection of objects (functions, variables etc.). An environment is created when we first fire up the R interpreter. Any variable we define, is now in this environment.

What all things R environment includes?

The environment is a virtual space that is triggered when an interpreter of a programming language is launched. Simply, the environment is a collection of all the objects, variables, and functions. Or, Environment can be assumed as a top-level object that contains the set of names/variables associated with some values.

How do I create a new environment in R?

To create an environment manually, use new. env() . You can list the bindings in the environment's frame with ls() and see its parent with parent. env() .


1 Answers

Well, from the ?parent.frame help page

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. sys.parent returns the number of the parent frame if n is 1 (the default), the grandparent if n is 2, and so on

and also

Strictly, sys.parent and parent.frame refer to the context of the parent interpreted function. So internal functions (which may or may not set contexts and so may or may not appear on the call stack) may not be counted, and S3 methods can also do surprising things.

So the parent.frame refers to the environment where the function was called from, not where it was defined.

For example

parentls <- function() {
  ls(envir=parent.frame())
}

a<-function() {
    x <- 5
    parentls()
}

b <- function() {
    z <- 10
    parentls()
 }

a()
# [1] "x"
b()
# [1] "z"
parentls()
# [1] "a"        "b"        "parentls"

Here, parentls() does an ls() in the parent.frame. And when run from within a() or b() we only see the variables within those functions. When called by itself, it simply gives you all the variables in your global environment just as if you called ls() by itself.

You can read more about parent frames in the Closure section or Calling Environment section of Hadely's Advanced R.

like image 59
MrFlick Avatar answered Oct 20 '22 17:10

MrFlick