[R] programming advice?

Duncan Murdoch murdoch at stats.uwo.ca
Fri Apr 21 16:57:04 CEST 2006

On 4/21/2006 10:45 AM, Charles Annis, P.E. wrote:
> Dear R-helpers:
> I am doing some exploratory programming and am considering a routine that
> has several other routines defined within it, so that I can avoid a large
> and messy global re-programming to avoid naming conflicts.  
> My question is this:  Because it is interpreted, does R have to re-build
> these internal routines every time the new routine is called?  I'm not
> overly worried right now about speed, but since my test cases currently run
> for several minutes (which is a long time to me) I don't want to learn a
> lesson the hard way that you, kind readers, might help me avoid.

I don't know the exact breakdown of the timing, but much of the work is 
done only once, when the source is parsed.  At that point the outer 
function will be created in a structure parts of which are more or less 
identical to the structure of the functions that it creates within it. 
Then when it executes, copies need to be made and wrapped up as objects 
of their own.  Only the latter work needs to be repeated on every call.

I'd say avoiding naming conflicts is probably not a good enough reason 
on its own to use nested functions.  You're better off putting your code 
in a package with a NAMESPACE if that's your goal.  The main reason to 
use nested functions is for clarity:  if some part of the work of a big 
function is neatly encapsulated in a small nested function, then do it. 
  Those nested functions have access to the evaluation environment of 
their enclosing function.

There are other reasons for nested functions (e.g. to create functions 
with static storage), but they are less common than doing it just to 
make the code clear.

Duncan Murdoch

More information about the R-help mailing list