Whereas against repeat cycles in R?

I was interested to know what the difference between the while loop and loop repetition in R is, apart from the syntax. Are there specific cases that I must follow to decide which one to use? (For example, is there a difference similar to using for loops for functions versus application loops?)

From my reading of the documentation, I would prefer a while loop, since the interrupt condition is next to the while command, although I think the β€œrepeat” loop looks a bit more flexible.

Best Ben

+7
r
source share
2 answers

Command syntax can be seen in ?Control :

 while(cond) expr repeat expr 

This makes it clear that while checks the condition to determine when to end the loop, but repeat requires you to explicitly specify the break loop yourself and can be anywhere in the body of the loop. Depending on where you place your break statement, repeat can do other parts of the iteration compared to while .

Consider these 2 forms of the same cycle:

 i <- 0 repeat {if (i==2) break;print(i);i<-i+1} [1] 0 [1] 1 i [1] 2 i <- 0 while (i!=2) {print(i);i<-i+1} [1] 0 [1] 1 i [1] 2 
+8
source share

In a context other than the R loop, repeat , the condition is checked at the end of each iteration, while the while checks it at the beginning of each iteration. Thus, a repeat performs at least one iteration, while a while cannot perform any iteration if the condition is not met. This is the difference.

+6
source share

All Articles