Programming Outside the Box: A Recursive Function in R

March 11, 2011

(This article was first published on Milk Trader, and kindly contributed to R-bloggers)

I heard a talk given by Ruby creator Yukihiro Matsumoto where he was rambling about how he came about becoming a programming language developer. He mentioned an important milestone as being his grasp of the idea behind recursion. I’ve kept that in mind and decided to dig into the idea a little bit and was pleased to discover something quite clever.

If you need to loop over some data set, you essentially have two options. Control flow iteration, which uses your common for loops and the like, and recursion. At first blush, recursion is very mysterious. The canonical example is the factorial() function where you multiply an integer by all the integers less than it and stop at 1. You remember from high school:  5! = 5x4x3x2x1.

I’ve written the following R implementation of it below:

factorial <- function(x){
        return( 1)

If you need to stare at it for a while, you’re not alone. How does a function call itself? Shouldn’t this simply blow up with a laundry list of errors at minimum and at worse a complete crash of your computer?  Well, actually it works. Try it. This is how it flows:


I thought to see how R prefers to implement the factorial() function and found my answer in the gregmisc package. This is the code for its factorial() function:

function (x) 
gamma(x + 1)

Okay, so what is the gamma() function? From the R help files, I got this definition:

Γ(x) = integral_0^Inf t^(x-1) exp(-t) dt

At some point I need to have the ability to blog functions in common mathematical notation and add some clarity to a dense concept, but for now that’s all I got. To be honest, if I had to explain the gamma function for 5 minutes, I would fail. At minimum though, I think mine is simpler.

UPDATE: Best wishes to Matz and his native Japan. May damage be minimized and recovery swift.

To leave a comment for the author, please follow the link and comment on their blog: Milk Trader. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...


Comments are closed.


Mango solutions

plotly webpage

dominolab webpage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training




CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)