Loops in R: Think different

[This article was first published on Revolutions, 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.

Especially for programmers that come to R from other languages, R sometimes gets dinged about the speed of its for loops. But a lot of the time, where you might have needed an iterative loop in another language to solve a specific task, you don't need a for loop in R at all.  Often, there's a pre-build function to accomplish the specific task at hand. Other times, you can use the implicit iteration of vector or matrix operations, which is much faster than using an explicit loop. And in other cases, you can use some of R's other looping constructs (like apply and lapply, for example) to achieve a similar goal more elegantly.

Basically, when it comes to looping in R, it's often best to think beyond the basic for loop. This post from Yihui Xie explains this point well: students, when asked to code an iterative task in R, often turned to a for loop when another method would have required less code and run faster. The alternate formulations makes for an educational example for all R programmers, not just students.

Statistics, R, Graphics and Fun: On the Gory Loops in R



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 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.

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)