I have a question about function environments in the R language. I know that everytime a function is called in R, a new environment E is created in which the function body is executed. The parent link of E points to the environment in which the function was created.
My question: Is it possible to specify the environment E somehow, i.e., can one provide a certain environment in which function execution should happen?
In R, the environment() function returns the environment associated with a given function or formula. An environment is a collection of objects such as functions, variables, and so on. Whenever we hit up the R interpreter, an environment is created.
To declare a user-defined function in R, we use the keyword function . The syntax is as follows: function_name <- function(parameters){ function body } Above, the main components of an R function are: function name, function parameters, and function body.
A function has an environment that can be changed from outside the function, but not inside the function itself. The environment is a property of the function and can be retrieved/set with environment()
. A function has at most one environment, but you can make copies of that function with different environments.
Let's set up some environments with values for x.
x <- 0
a <- new.env(); a$x <- 5
b <- new.env(); b$x <- 10
and a function foo
that uses x
from the environment
foo <- function(a) {
a + x
}
foo(1)
# [1] 1
Now we can write a helper function that we can use to call a function with any environment.
with_env <- function(f, e=parent.frame()) {
stopifnot(is.function(f))
environment(f) <- e
f
}
This actually returns a new function with a different environment assigned (or it uses the calling environment if unspecified) and we can call that function by just passing parameters. Observe
with_env(foo, a)(1)
# [1] 6
with_env(foo, b)(1)
# [1] 11
foo(1)
# [1] 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With