Site icon R-bloggers

Speed up for loops in R

[This article was first published on minimalR.com » r-bloggers, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Are your for loops too slow in R ? Are loops that should take seconds actually taking hours ?

As I found out recently, how you structure your code can make a huge difference in execution times. Fortunately making a few small changes to your code can speed up these loops by several orders of magnitude.

This Stack Overflow post goes through a number of ways to optimise your for loops – I only implemented the first method and my loop run time went from over an hour to less than 10 seconds !!!

The secret ? to loop over a vector rather than data frames as R is optimised for vector and matrix operations.

To leave a comment for the author, please follow the link and comment on their blog: minimalR.com » r-bloggers.

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.