[R] environment

Gabor Grothendieck ggrothendieck at gmail.com
Wed Apr 26 13:23:43 CEST 2006


A third possibility is to using the proto package and define
a proto object (an environment with special meaning for $)
containing the two components .x and g like this:

library(proto)
p <- proto(.x = 2, g = function(.) { print(.$.x); .$.x <- 3 })
p$.x  # 2
print(p$g())  # 2, 3
p$.x # 3

or you can write the print statement as with(., print(.x))

On 26 Apr 2006 11:02:58 +0200, Peter Dalgaard <p.dalgaard at biostat.ku.dk> wrote:
> Romain Francois <francoisromain at free.fr> writes:
>
> > Hi,
> >
> > Consider the code :
> >
> > g <- function(){
> >   print(.x)
> >  .x <- 3
> > }
> >
> > f <- function(){
> >   environment(g) <- environment()
> >   .x <- 2
> >   g()
> >   .x
> > }
> >
> >  > f()
> > [1] 2
> > [1] 2
> >
> >
> > I would like f() to return 3. How can I do that ? Am I completely out of
> > place ?
> > Doing that, I want to avoid to pass .x as a parameter in f, because in
> > real life .x is pretty big and g() is called over and over in a loop.
>
> If you want to assign into the environment of g, you'll need <<- ,
> otherwise you  assign to a local variable.
>
> Another possibility involves assign(..., parent.frame())

And a third possibility is:

library(proto)




More information about the R-help mailing list