[R] Forcing a break/end in a loop

Roger Peng rpeng at stat.ucla.edu
Sun Jul 28 00:53:39 CEST 2002


You could use either stop(), break, or return(), depending on what the
rest of your program looks like.  For example:

x <- c(1:5, -6, 7:10)    # say due to mis-typing

for (i in 1:10){
  if(is.na(log(x[i]))==FALSE) print("OK")
  else stop("Not OK check your values") }
}


-roger
_______________________________
UCLA Department of Statistics
rpeng at stat.ucla.edu
http://www.stat.ucla.edu/~rpeng

On Sat, 27 Jul 2002, Adaikalavan Ramasamy wrote:

> This is probably some basic programming question. I am testing a complicated
> and time consuming loops. I have also built in an internal check for the
> values, which prints something like OK or Not OK to the screen so that I can
> see if anything has gone wrong.
> 
> There errors are not logical errors so basically the loop runs to
> completion. Is there a way of forcing the loop to stop/exit immediately when
> it first fails my internal check ?
> 
> A simplified example follows:
> 
> x <- c(1:5, -6, 7:10)    # say due to mis-typing
> 
> for (i in 1:10){
>  { if(is.na(log(x[i]))==FALSE) print("OK")
>    else print("Not OK check your values") }
> }
> 
> The output of the above is "OK", .... , "Not OK check your values", "OK",
> ...,"OK".
> So I want the loop to stop when the 6th value fails.
> 
> This would save me a lot of time waiting for the loop to end just because I
> made an typing error.
> Many thanks.
> 
> Adai.
> 
> 
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
> 

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list