Speed up R "for" loops 50x with Rcpp

June 23, 2011

(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 their blog: Revolutions.

R-bloggers.com 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...

Tags: , ,

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training



CRC R books series

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)