[R] Fwd: Evaluating a function within a pre-defined environment?

Gabor Grothendieck ggrothendieck at gmail.com
Wed Dec 9 23:36:08 CET 2009


e <- new.env()
e$x <- 2
f <- function(a, e) { e$x <- e$x + a; e$x }
f(3, e)
e$x # 5

Another way to accomplish this is to use the proto package which puts
the whole thing into an object oriented framework.  See
http://r-proto.googlecode.com

library(proto)
p <- proto(x = 2, f = function(this, a) { this$x <- this$x + a; this$x })
p$f(3) # 5


On Wed, Dec 9, 2009 at 4:54 PM, David Reiss <dreiss at systemsbiology.org> wrote:
> Hi all,
>
> I have a somewhat confusing question that I was wondering if someone
> could help with. I have a pre-defined environment with some variables,
> and I would like to define a function, such that when it is called, it
> actually manipulates the variables in that environment, leaving them
> to be examined later. I see from the R language definition that
>
> "When a function is called, a new environment (called the evaluation
> environment) is created, whose enclosure (see Environment objects) is
> the environment from the function closure. This new environment is
> initially populated with the unevaluated arguments to the function; as
> evaluation proceeds, local variables are created within it."
>
> So basically, I think I am asking if it is possible to pre-create my
> own "evaluation environment" and have it retain the state that it was
> in at the end of the function call?
>
> Example:
>
> e <- new.env()
> e$x <- 3
> f <- function(xx) x <- x + xx
>
> can I then call f(2) and have it leave e$x at 5 after the function
> returns? I know that
>
> environment(f) <- e
>
> goes part of the way, but I would like to let the function also write
> to the environment.
>
> Thanks for any advice.
>
> --David
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list