[R] Odp: Programming: loop versus vector oriented

Petr PIKAL petr.pikal at precheza.cz
Mon Sep 20 11:55:57 CEST 2010


Hi Jan

r-help-bounces at r-project.org napsal dne 17.09.2010 12:43:40:

> Hello Petr,
> 
> > but I think this is how your code really works. Did you try it?
> 
> it does, but the R documentation says somewhere:
> "Warning: for() loops are used in R code much less often than in
> compiled languages. Code that takes a `whole object' view is likely to
> be both clearer and faster in R."

Yes and no. For loops are not per se slower. AFAIK lapply or apply is only 
wrapped loop. But especially people coming from modern compiled languages 
are used to loops and try to use R like C, which usually ends up in doing 
things which can be done by built in function by for loop. Consider 
counting numbers from 1 to 100000.

x <- 1:100000

# loop
> system.time(for(j in 1:100) {
+ r1<-0
+ for (i in 1:100000) r1<-r1+x[i]
+ })
   user  system elapsed 
  15.42    0.01   15.49 

# sum
> system.time(for(j in 1:100) r2<-sum(as.numeric(x)))
   user  system elapsed 
   0.16    0.05    0.20 

#simple math
> system.time(for(j in 1:100) r3<-100000*100001/2)
   user  system elapsed 
      0       0       0 
> 
> all.equal(r1, r2, r3)
[1] TRUE

So if you do not care about built in functions and simple math you can use 
loop but you have to wait.

> 
> So I am wondering in what way the "whole object view" could be applied
> to my function.

I offered an option to split vectors according to thresholds to list and 
use only for cycle with three loops instead of performing as many loops as 
is length of your vector and checking each number n times inside of a 
loop.

If it is quicker depends on how long are your vectors. 

If you want to profile your functions see

?Rprof

Regards
Petr

> 
> Best regards,
>    Jan
> 
> > > The function should work on the nth elements of the two input 
vectors
> > > and put the result into the nth element of the output vector. So it
> > > would work like c <- a + b, only instead of '+' there are more 
complex
> > > calculations.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list