[R] How to move an internal function to external keeping same environment?

Matthieu Stigler matthieu.stigler at gmail.com
Mon Nov 15 13:48:40 CET 2010


I have within a quite big function foo1, an internal function foo2. Now, 
in order to have a cleaner code, I wish to have the internal foo2 as 
"external". This foo2 was using arguments within the foo1 environment 
that were not declared as inputs of foo2, which works as long as foo2 is 
within foo1, but not anymore if foo2 is external, as is the case now.

Now, I could add all those arguments as inputs to foo2, but I feel if 
foo2 is called often, I would be copying those objects more than 
required. Am I wrong?

I then used this to avoid to declare explcitely each argument to foo2:

   environment(foo2)<-new.env(parent =as.environment(-1))


foo2<-function(x)  x*b

This works. But I wanted to be sure:

-am I right that if I instead declare each element to be passed to foo2, 
this would be more copying than required? (imagine b in my case a heavy 
dataset, foo2 a long computation)
-is this lines "environment(foo2)<-new.env(parent =as.environment(-1))" 
the good way to do it or it can have unwanted implications?

Thanks a lot!!


More information about the R-help mailing list