Skip to content
Prev 132833 / 398502 Next

Conditionally incrementing a loop counter

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