Accessing the execution environment of a function in R

r function environment
how are free variables in r functions resolved?
r assign global environment
parent frame r
r list environment variables
r current environment
r/environment reddit
r get variable from global environment

I have a function that "prepares" stuff for the rest of the program. for example, the following function which defines two functions:

prepare = function() {
    f = function(x) x+1
    g = function(x) x+2

of course that once the functions executes the functions f and g are not available any more. They where defined in the execution environment of "prepare", which is gone once the function completes its execution.

My question is, is there any way to keep or to access that execution environment?

The scenario is that I get that "prepare" function from the outside, so can't edit its code, and I want to execute it and use whatever it does in the following manner:

my_function = function(prepare) {
    # the prepare function is supplied by the user
    prepare()  #this should define the f and g functions as above
    f(3)   # this wouldn't work normally, since f is defined inside prepare

is there a way to achieve that? that is, making "prepare" affect the calling environment, rather its execution environment?


found a workaround with use of body() which allows accessing the expressions inside a function, and build new expressions out of them, so I build a new function based on the "bodies" fo the "prepare" function and the "original" function. The real solution, as I thought through the problem was to use "aspect orientation". but unfortunately R is not aspect oriented language. maybe an idea for a new package :-)

If you modify the prepare function a bit:

prepare = function() {
    f = function(x) x+1
    g = function(x) x+2

you can access the functions like this:


# [1] 26

Or you can use <<-, which puts the function to global environment:

prepare = function() {
     f <<- function(x) x+1
     g <<- function(x) x+2

Environments · Advanced R., Return the execution environment of a function by going over the execution environments of all functions in the calling chain. emptyenv()function can be used to get the empty environment. the current environment, accessible via environment()function. When working interactively, the search()function can be used to list all parents of the global environment. All objects in these environments are accessible from the interactive workspace.

>prepare<-function() return(list(f=function(x) x+1, g=function(x) x+2))
> p<-prepare()
> p$f(1)
[1] 2
> p$g(1)
[1] 3
Edit after a long time

I had to come back to this for myself...

> prepare
function(x) { p = function(x) 5*x; q= function(x) x^2 }
> with( new.env ( eval( parse(text=deparse(body(prepare))) ) ) , { print(p(5)); print(q(2))} )
[1] 25
[1] 4

get_fun_env: Return the execution environment of a function in , globalenv() function can be used to get the global environment. calling a function creates an execution environment that stores variable  The envnames package is capable of accessing the name of any environment –be it a system environment, a package, a namespace, a user-defined environment, or even a function execution environment– by way of a lookup table that maps environment names to their memory addresses. The lookup table is created every time one of the 11 visible

Using the fact that environment(fun) returns the enclosing environment of a function --which defines how the function finds objects--, the following use of environment() allows you to access the functions defined inside prepare():

prepare = function() {
  f = function(x) x+1
  g = function(x) x+2

my_function = function(preparefun) {
  # We call the prepare() function supplied by the user
  # that defines functions f() and g() and store its returned value
  fun_returned_by_prepare = preparefun()
  cat("Result of calling function f(3) defined in function prepare():", environment(fun_returned_by_prepare)$f(3), "\n")
  cat("Result of calling function g(3) defined in function prepare():", environment(fun_returned_by_prepare)$g(3), "\n")


which yields:

Result of calling function f(3) defined in function prepare(): 4 
Result of calling function g(3) defined in function prepare(): 5

HOWEVER, this works ONLY because the prepare() function returns a function (in this case function g() which is defined at the last line of prepare() and therefore returned), implying that the call to environment() on the object returned by prepare() (fun_returned_by_prepare) retrieves the enclosing environment of function g() defined in prepare(), which happens to be the execution environment of prepare()!

If the returned value of prepare() were not a function, the above code no longer works.

On a side note, in case the following comes handy for some other application you may have: I wrote a package called envnames that, among other things, allows you to retrieve the execution environment of a function by its name (get_fun_env()). In order for this to work however, the function has to be part of the calling stack at the place where get_fun_env() is called, which unfortunately is not the case in your above example.

Environments in R: an exploration, Environments and Functions When a function is called in R, a new a function was created in the execution environment (for example, in the global environment), then the parent environment will not be the same as the calling environment. Function environments revises R’s scoping rules in more depth, showing how they correspond to four types of environment associated with each function. Binding names to values describes the rules that names must follow (and how to bend them), and shows some variations on binding a name to a value.

Environments and Functions - R in a Nutshell [Book], You can use R's $ syntax to access an object in a specific environment. We'll use the following function to explore R's runtime environments. We want to know​  The thing to look out for are any uses of the function keyword because functions capture a reference to the current execution environment as their closure (their static or lexical environment). Any such function returned in a value can therefore keep the so-called transient execution environment alive indefinitely.

8 Environments, What is the enclosing environment of a function? Why is it Access the global environment with globalenv() and the current environment with environment() . Note that the parent of the execution environment is the function environment. Cloud Functions Execution Environment. Cloud Functions run in a fully-managed, serverless environment where Google handles infrastructure, operating systems, and

7 Environments, Environment can be thought of as a collection of objects (functions, variables etc.)​. The top level environment available to us at the R command prompt is the global Global variables are those variables which exists throughout the execution of a program. It can be changed and accessed from any part of the program. Although the parent environment for a function is not always the environment in which the function was called, it is possible to access the environment in which a function was called. [ 23] L Like many other languages, R maintains a stack of calling environments. (A stack is a data structure in which