Skip to content

Recursive user-defined methods in R scripts - upper bound on nested calls?

2 messages · Rick Reeves, Barry Rowlingson

#
Heres a question regarding R script development:

First, the scenario - 
I'm working on a method to aggregate voronoi cells
into larger polygons based on a scoring criteria;
part of the solution now uses a recursive R function
(written in R script). The calling program fails 
unceremoniously (no messages, just 'into the ether')
after about 50 nested recursive calls. Looks like a 
stack overflow to me, but I am now checking my dataset
for anomolies that may cause the failure.

I seem to recal recursive C routines crashing after
50 or so nested calls on Unix workstations, so this
may be unavoidable

The question: Has anyone explored the limits of 
recursive R function calls? I coded the recursive 
method to have a minimal run-time memory footprint. 

Is there a way to ask for more resources (stack space)
in the R run-time environment? 

Any thoughts are welcome!

Regards, 
Rick Reeves

Scientific Programmer / Quantitative Analyst
National Center for Ecological Analysis and Synthesis
University of California, Santa Barbara
805 892 2534
reeves at nceas.ucsb.edu
#
Rick Reeves wrote:

            
There's a limit on how deep expressions can go:

  > recurse
  function(n){if(n==1){return(0)}else{return(recurse(n-1))}}

  > recurse(99)
  [1] 0

  but this usually gives an error when it goes too far:

  > recurse(100)
  Error in recurse(n - 1) : evaluation nested too deeply: infinite 
recursion / options(expression=)?
> options(expressions=1000)
  > recurse(100)
  [1] 0

Might not explain why your code dies silently, unless the error is being 
trapped inside a 'try'...

Baz