[R] Problems accessing environment() in function

Duncan Murdoch murdoch.duncan at gmail.com
Wed May 2 20:07:00 CEST 2012


On 02/05/2012 12:59 PM, Heiko Neuhaus wrote:
> Thanks a lot for your answer!
>
> >>  ------------------------------
> >>
> >>  test1<- function(a, b, c)
> >>  {
> >>  x<- as.list(environment())
> >>  print ("hi from test1!")
> >>  test2(a = a, b = b, c = c)
> >
> >  You are rying to pass a, b, c here and hence R tries to insert those
> >  into the environment of test2 once it is called, you have not passed
> >  arguments to your test1 call.
> >
> >  Uwe Ligges
>
> I am aware that I am passing non existing arguments here, which is why
> my method of creating a list of the environment "as.list(environment())"
> seems to fail in this case.
>
> What I need is a way to just skip non existing objects when I create my
> list. In my given example I was intending to receive an empty list,
> since no valid arguments were passed to test2().
>
> In other words: I want a list containing all _existing_ variable/value
> combinations and just skip the missing ones.

That's hard to do, because missing arguments exist, they just have a 
special value to signal that they were missing.  The missing() function 
tests for that value, but it is picky about its arguments.  So if you 
want to do all of this in R you probably need some tricky programming, 
like this:

f <- function(a,b,c) {
   names <- ls(environment())  # get all the names
   result <- list()
   for (n in names) {
     if (!do.call(missing, list(as.name(n))))
       result[n] <- get(n)
   }
   result
}

If you put the ls() call later, you'll pick up other local variables 
(names, result, n) as well.

Duncan Murdoch



More information about the R-help mailing list