title: Are recursive functions used in R?
body: <p>The canonical function to demonstrate recursion is the factorial() function. I tried a simple implementation of it myself and came up with this:</p>
  
  <pre><code>factorial &lt;- function(x){
  
  if(x==1)
      return( 1)
  else
      return(x*factorial(x-1))
  
  }
  </code></pre>
  
  <p>From my survey of the topic, there seems to be some debate about whether it's better to use recursion or simple iteration. I wanted to see how R implements it and found a factorial() function in the gregmisc package. I thought I'd find something like my implementation or instead a regular iteration. What I found this:</p>
  
  <pre><code>&gt; factorial
  function (x) 
  gamma(x + 1)
  &lt;environment: namespace:base&gt;
  </code></pre>
  
  <p>So the answer to my question of whether R prefers recursion or iteration is "neither". At least in this implementation. Are recursive functions avoided in R for good reason?</p>
  
  <p>Update:</p>
  
  <p>gregmisc version:</p>
  
  <pre><code>&gt;ptm &lt;- proc.time()
  &gt; factorial(144)
  [1] 5.550294e+249
  &gt; proc.time() - ptm
     user  system elapsed 
    0.001   0.000   0.001 
  </code></pre>
  
  <p>my version:</p>
  
  <pre><code>&gt; factorial(144)
  [1] 5.550294e+249
  &gt; proc.time() - ptm
    user  system elapsed 
    0.002   0.001   0.006 
  </code></pre>