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).
The simplest solution is to use the environment when referencing the object:
You would need to assign
zto your environment as well.One other option would be to
attachyour environment so that the variables can now be used directly.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
zis not in the scope of thewithcall). 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: