Loops in R: Think different

November 15, 2010

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

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

Search R-bloggers


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)