What is the parent frame R

What is a parent frame R. By the way, what does a parent frame mean? I assume this is a defining environment instead of calling the environment, since R uses the lexical domain, but I'm not sure. Thanks.

+7
r
source share
1 answer

Ok, on the help page ?parent.frame

A parent frame for evaluating a function is the environment in which the function was called. It is not necessarily numbered one less than the frame number of the current estimate, and is not the environment in which the function was defined. sys.parent returns the number of the parent frame if n is 1 (default), grandparent if n is 2, etc.

and

Strictly, sys.parent and parent.frame refer to the context of the parent interpreted function. Thus, internal functions (which may or may not set contexts and therefore may or may not appear in the call stack) may not be taken into account, and S3 methods can also do amazing things.

Thus, parent.frame refers to the environment from which the function is called, and 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 ls() on parent.frame. And when starting from a() or b() we see only variables inside these functions. When it is called on its own, it just gives you all the variables in your global environment, as if you yourself called ls() .

You can learn more about parent frames in the Closure section or the Challenge "Environmental" section in Hadely Advanced R.

+12
source share

All Articles