Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do-while loop in R

I was wondering about how to write do-while-style loop?

I found this post:

you can use repeat{} and check conditions whereever using if() and exit the loop with the "break" control word.

I am not sure what it exactly means. Can someone please elaborate if you understand it and/or if you have a different solution?

like image 1000
Tim Avatar asked Dec 05 '10 07:12

Tim


People also ask

Does R have do while loop?

Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in R programming. In R programming, while loops are used to loop until a specific condition is met.

Do while () loop is?

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Do While and while do loop?

while loop is similar to a while loop, except that a do... while loop is guaranteed to execute at least one time. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.


2 Answers

Pretty self explanatory.

repeat{   statements...   if(condition){     break   } } 

Or something like that I would think. To get the effect of the do while loop, simply check for your condition at the end of the group of statements.

like image 93
A Salcedo Avatar answered Oct 10 '22 05:10

A Salcedo


See ?Control or the R Language Definition:

> y=0 > while(y <5){ print( y<-y+1) } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 

So do_while does not exist as a separate construct in R, but you can fake it with:

repeat( { expressions}; if (! end_cond_expr ) {break} ) 

If you want to see the help page you cannot type ?while or ?repeat at the console but rather need to use ?'repeat' or ?'while'. All the "control-constructs" including if are on the same page and all need character quoting after the "?" so the interpreter doesn't see them as incomplete code and give you a continuation "+".

like image 33
IRTFM Avatar answered Oct 10 '22 03:10

IRTFM