[R] How to set a former environment?
Duncan Murdoch
murdoch at stats.uwo.ca
Tue Apr 4 00:04:58 CEST 2006
On 4/3/2006 1:44 PM, Werner Wernersen wrote:
> Hi,
>
> I probably misunderstand the entire concept of
> environments in R. I now have a list of environments
> in which each has a number of variables. What I want
> to do is to apply a function on each of those
> environments which adds additional variables to that
> particular environment. Is there a way to set the
> environment of the function so that also the variables
> newly created in the function are added to the
> environment?
>
> Right now I do
> environment(FN) <- oldEnvironment
> before I call the function and the function operates
> on the old environments variables but the newly
> created ones are not in the old environment.
The line
environment(FN) <- oldEnvironment
sets the closure of the function, i.e. the parent of the evaluation
environment. Assignments within the function are made within the
evaluation environment, which usually disappears when the function
returns. (An exception to this: if you create and return a function
within a function, the closure of the new one is by default the
evaluation environment of the old one, so it will outlast the outer
function call.)
Generally there is no way to set the evaluation environment of a
function, but you could write a function that copied things from it
somewhere else, e.g.
copyObjects <- function(fromEnvironment, toEnvironment) {
names <- ls(fromEnvironment)
for (n in names) assign(n, get(n, env=fromEnvironment),
env=toEnvironment)
}
and then putting
copyObjects(environment(), parent.env(environment()))
in a function will copy all the locals into the parent. More simply,
you can do assignments directly to the parent environment using
assign("name", env=parent.env(environment()))
More information about the R-help
mailing list