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).
You only need to make one change to make your example work - redefine your function to use
substitute()
to 'fix' the desired values within the scope off()
:This can quickly get murky especially since you can even include assignment statements within
substitute()
(for instance, replacex+z
withy <- x+z
, not that this is entirely relevant here) but that choice can be made by the developer...Additionally, you can replace
list(z=z)
in the substitution expression above withenvironment()
(e.g.,substitute(x+z,environment())
) as long as you don't have conflicting variable names between those passed tof()
and those residing in your 'env', but you may not want to take this too far.Edit: Here are two other ways, the first of which is only meant to show the flexibility in manipulating environments and the second is more reasonable to actually use.
1) modify the enclosing environment of 'env' (but change it back to original value before exiting function):
2) Force evaluation of 'z' in current environment of the function (using
environment()
) rather than letting it remain a free variable after evaluation of the expression,x+z
, in 'env'.Depending on your desired resolution order, in case of conflicting symbol-value associations - e.g., if you have 'x' defined in both your function environment and the environment you created, 'y' (which value of 'x' do you want it to assume?) - you can instead define the function body to be
with(env,with(environment(),x+z))
.The simplest solution is to use the environment when referencing the object:
You would need to assign
z
to your environment as well.One other option would be to
attach
your 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
z
is not in the scope of thewith
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:mind the parentheses:) The following will work: