Re: [R] Conditionally incrementing a loop counter

From: Nordlund, Dan (DSHS/RDA) <NordlDJ_at_dshs.wa.gov>
Date: Thu, 27 Dec 2007 15:58:46 -0800

> -----Original Message-----
> From: r-help-bounces_at_r-project.org
> [mailto:r-help-bounces_at_r-project.org] On Behalf Of Mike Jones
> Sent: Thursday, December 27, 2007 1:35 PM
> To: r-help_at_stat.math.ethz.ch
> Subject: [R] Conditionally incrementing a loop counter
>
> Hi,
> I am trying a for loop from 1 to 100 by 1. However, if a
> condition does
> not get met, I want to "throw away" that iteration. So if my loop is
> for (i in 1:100)
> and i is say, 25 and the condition is not met then I don't
> want i to go
> up to 26. Is there a way to do that? I can't seem to
> manually adjust i
> because from what I understand, R creates 100 long vector and
> uses that
> to "loops thru" and I'm not sure how to get at the index of
> that vector.
> Any suggestions? Thanks in advance.
>
>
>
>
> Mike Jones
> Westat
> 1650 Research Blvd. RE401
> Rockville, MD 20850
> Ph: 240.314.2312
>

Mike,

A question about R from SAS Mecca ??? :-)

I would use Peter Dalgaard's suggestion of a 'while' type loop along with the 'next' loop control, something like this

i <- 1
iter_number <- 0
while(i<=10){

   iter_number <- iter_number + 1
   x <- runif(1)
   if (x > 0.7) next
   cat(iter_number, i, x, "\n")
   i <- i+1
}

Where iter_number allows you to print out loop number each time the condition is met (for instructional purposes only). When the if condition is met, the next construct skips back to the top of the while loop without executing the rest of the statements.

Hope this is helpful,

Dan

Daniel J. Nordlund
Research and Data Analysis
Washington State Department of Social and Health Services Olympia, WA 98504-5204    



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 28 Dec 2007 - 00:00:59 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 28 Dec 2007 - 00:30:21 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.