[R] alternative way to loop

Duncan Murdoch murdoch at stats.uwo.ca
Tue Sep 11 15:16:43 CEST 2007


On 9/11/2007 8:54 AM, kevinchang wrote:
> I heard that if-loop may result in errors if we are going to loop for a lot
> of times. 

I don't know what you mean by an "if-loop", but if doing it lots of 
times caused an error, that would likely be a bug in R.  And I know of 
no such bug.

 > And sum() can be the alternative way to do this kind of  hugbe
> looping. But I haven't figure out how . Can someone please give me an
> concrete example of using sum() for this purpose? 

total <- sum(1:10)

is a much faster way to evaluate

total <- 0
for (i in 1:10) total <- total + i

but neither one should cause an error (and neither one involves an 
"if-loop").

Duncan Murdoch



More information about the R-help mailing list