AaronP AaronP - 24 days ago 5
R Question

Binding functions to environment to access stored variables, what are the downsides?

Problem:
I need a function which takes only one argument, but needs access to some other variables. I don't want to store these in the

.GlobalEnv
.

Current Solution:
Use a function which takes all needed arguments, that create another function which adapt the environment.

Example:

library(rlang)
foo <- function(a, b){
bar <- function(c){
out <- a + b + c
out
}
set_env(bar, get_env())
bar
}
bar <- foo(1, 2)
bar(3)


I strongly believe that this approach have downsides, but I can't put my finger on what these downsides might be. I would be happy if you could help me.

Answer Source

There's nothing wrong with this. You don't need rlang either:

foo <- function(a, b)
{
    function(c) a + b + c
}

bar <- foo(1, 2)
bar(3)

The returned value of foo will be another function, whose environment is the one in which it was defined. That happens to be foo's environment.

The only time this might be an issue is if there are other objects in foo that interfere with how things should work. To guard against this, you can explicitly create a new environment that is distinct from foo's environment:

foo <- function(a, b)
{
    bar <- function(c) a + b + c
    environment(bar) <- new.env(parent=globalenv())
    bar
}

but this should rarely, if ever, be necessary.