Speed up R "for" loops 50x with Rcpp

June 23, 2011
By

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

Christian Gunning has a great example of using Rcpp to speed up a for loop in R. For his agent-based simulation, Christian needed to repeatedly call the rbinom function in a loop. (Unfortunately, you can't pass a vector to the size argument, which would have solved the problem.) Using the aaply function (from the plyr package) took about 38 sections for 10,000 simulations: aaply gives you nice concise code, but it's bit like using a hammer to crack a walnut in this case. An explicit for loop took just over a second. But rewriting the body of the loop in C++ (but still calling R's native binomial RNG, via the standard R API) reduced the time by a factor of over 50 compared to the for loop: down to 0.021 seconds. cxxfunction in the inline package makes it super simple to incorporate C++ code into your R loops (provided you know C++ of course) -- see Christian's full post at the link below to see how it's done. 

Life in Code: Efficient loops in R -- the complexity versus speed trade-off

To leave a comment for the author, please follow the link and comment on his blog: Revolutions.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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...

Tags: , ,

Comments are closed.