do-while loop in R
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 "+".
Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).
df <- data.frame(X=c(), R=c()) x <- x0 continue <- TRUE while(continue) { xi <- (11 * x) %% 16 df <- rbind(df, data.frame(X=x, R=xi)) x <- xi if(xi == x0) { continue <- FALSE } }