[R] How to share variables

Sergio Martino s.martino at tno.it
Mon Aug 21 09:23:56 CEST 2006

Thanks for your fast replay and sorry for my late one (I was on holidays)

The structure I would like to emulate (the fortran common statement) is a
different from what you are describing.

The examples "scoping" and the links to OO programming show the use of local
variable which are tied to the object itself.

My need is to have a group of (big) variable shared among some function in a
way that they can be accessed freely.

More useful is the environment example you reported. The only problem is
that it seems I need to replace the whole environment of the function. What
I need to investigate is where the variables created inside the inner
function (myfun) go. If they belong to the enviroment (e) I will get a
mix-up of variables with side effect (variables with the same name) and it
will be a pain.

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.

I need to experiment a little bit.


> On 8/2/06, Sergio Martino <s.martino at tno.it> wrote:
> > Hi,
> >
> > I would like to realize in R a structure like the fortran common ie a
way to
> > declare some variable that can only be accessed by all the functions
> > need to.
> >
> > Browsing the archive it seems that the simplest way is to declare the
> > variables and the functions in a big function which wraps all. But this
> > impratical when the functions are big.
> There is a demonstration of that found by issuing the command:
> demo(scoping)
> >
> > The environments seems to do the trick but I am not enough familiar with
> > them to make my ways out.
> Yes place your data in an environment as shown and then for
> each function that is to access the environment should have
> its environment set accordingly:
> e <- new.env()
> e$dat <- 1:3
> myfun <- function(x) sum(x + dat)
> environment(myfun) <- e
> myfun(10)  # fun can access dat
> Realize that what you are trying to do is to create a sort of object
> oriented structure with the data being the objects and the functions
> being the methods.  The proto package provides some functionality
> to implement that and also supports delegation (similar to
> inheritance):
> library(proto)
> package?proto # all sources of info on proto
> # example - create proto object p with some data dat and a method fun
> p <- proto(dat = 1:3, fun = function(., x) sum(x + .$dat))
> # invoke method
> p$fun(10)  # runs fun.  fun has access to dat
> # create a child q of p and run fun
> # q overrides dat with its own dat while inheriting fun
> q <- p$proto(dat = 4:6)
> q$fun(10)
> Another possibility would be to look at the R.oo package which is
> another object oriented infrastructure based on environments.
> >
> > Is there any example or pointers to easy but complete environment usage?
> >
> > Thanks in Advance
> >
> > Sergio Martino

More information about the R-help mailing list