[R] How to share variables

Gabor Grothendieck ggrothendieck at gmail.com
Wed Aug 2 15:50:33 CEST 2006


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 which
> 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 is
> 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