Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functions and environments

Tags:

scope

r

Following the recent discussions here (e.g. 1, 2 ) I am now using environments in some of my code. My question is, how do I create functions that modify environments according to its arguments? For example:

y <- new.env()
with(y, x <- 1)
f <- function(env,z) {
    with(env, x+z)
}
f(y,z=1)

throws

Error in eval(expr, envir, enclos) : object 'z' not found

I am using environments to keep concurrently two sets of simulations apart (without refactoring my code, which I wrote for a single set of experiments).

like image 752
Eduardo Leoni Avatar asked Feb 03 '26 18:02

Eduardo Leoni


1 Answers

The simplest solution is to use the environment when referencing the object:

y <- new.env()
y$x <- 1
f <- function(env,z) {
    env$x+z
}
f(y,z=1)

You would need to assign z to your environment as well.

y <- new.env()
with(y, x <- 1)
f <- function(env,z) {
    assign("z", z, envir=env)
    with(env, x+z)
}
f(y,z=1)

One other option would be to attach your environment so that the variables can now be used directly.

y <- new.env()
with(y, x <- 1)
f <- function(env,z) {
    attach(env)
    y <- x + z
    detach(env)
    y
}
f(y,z=1)

This latter solution is powerful because it means you can use any object from any attached environment within your new environment, but it also means that you need to be very careful about what has been assigned globally.

Edit:

This is interesting, and I don't entirely understand the behavior (i.e. why z is not in the scope of the with call). It has something to do with the creation of the environment originally that is causing it to be outside the scope of the function, because this version works:

f <- function(z) {
    y <- new.env()
    with(y, x <- 1)
    with(y, x+z)
}
f(y,z=1)
like image 129
Shane Avatar answered Feb 06 '26 11:02

Shane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!