[R] How to share variables

Sergio Martino s.martino at tno.it
Tue Aug 22 11:45:01 CEST 2006


Hi

Thanks again. I hope not to waste to much of your time.

I delete some lines of your answer

> Each time myfun is run a new environment is created to hold
> its local variables.  The parent of that environment is e in
> this example by construction.  So e and the environment that
> is temporarily created to hold myfun's variables are distinct.

This means that the enviroment is duplicated, ie it is present twince in
memory?
I must keep some big variables and it will be a waste of memory; moreover if
I update a value it will be lost.

> > If I can use inside myfun the variable as e$dat (without changing the
> > enviroment (no environment(myfun) <- e statement)) than it will be ok.
>
> Yes you can.  You can either make sure that e is visible to myfun
> via normal scoping rules or pass it explicitly:
>
> e <- new.env()
> e$dat <- 1:3
> myfun <- function(x) sum(x + e$dat)
> myfun(10)
>

Hit!!!
It solves the problem.
A small drawback is that I need to modify the name of each occurrence of the
variable.


> # or passing e explicitly
>
> myfun2 <- function(x, e) sum(x + e$dat)
> myfun2(10, e)
>

Any overhead in passing the environment? Is it a pointer?

Sergio



More information about the R-help mailing list