How can I reference the local environment within a function, in R?
To get the current environment, just call environment()
.
In general, sys.frame
returns any of the environments currently on the call stack, and sys.nframe
returns the current depth of the call stack. sys.frames
returns a list of all environments on the call stack.
environment(f)
returns the closure environment for a function f
(where it will look for functions and global variables).
parent.env(e)
returns the parent environment where it will look if a symbol is not found in e
.
f <- function() { function() list(curEnv=environment(), parent=parent.env(environment()), grandParent=parent.env(parent.env(environment())), callStack=sys.frames(), callStackDepth=sys.nframe())}g <- function(f, n=2) if (n>2) g(f, n-1) else f()floc <- f() # generate a local functiong(floc, 3) # call it
This will call the local function floc
with a stack depth of 3. It returns a list with the current environment, it's parent (the local environment in f
), and it's grand parent (where f
was defined, so globalenv
). It also returns the list of stack frames (environments). These are the environments for the recursive calls in g
(except the last one which is the current environment of floc
).