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
All true. However, sometimes for loops are much easier to read if the performance penalty isn't too bad.
Posted by: Boris Shor | November 15, 2010 at 18:02
a powerful function I really like is which()
i <- which(x > a)
in combination with
x[-i]
(i<0!) loops often can be avoided
Posted by: wactbprot | November 16, 2010 at 13:25
@wactbprot, why do you need which()? Why not just use the negation operator on your logical vector?
Try this:
x<-sample( 1:10, 50, replace=TRUE)
a<-5
i <- which(x > a)
identical( x[-i], x[!x > a] )
Posted by: TM | November 19, 2010 at 12:54
@TM
I need which() here because I don't want to preach to the converted. Thats all.
The post we comment her speaks to "programmers that come to R from other languages". Don't you think that which() is a command "programmers that come to R from other languages" should look on?
Posted by: wactbprot | November 21, 2010 at 13:43
I came across the foreach package it has parallel processing capabilities.
Posted by: John | December 18, 2010 at 19:34