Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.