Nick
Nick

Reputation: 1106

R: How to decrease counter in for loop

I would like to do 10 iterations, but sometimes flag is bigger that 1. In this case I must to decrease variable i by 1 and calculate flag again. How to do this decrement?

    for(i in (1:n)){ 
    flag <- ... # some code
        if (flag > 1) {
         # some code
        } 
        #else decrement i <- i - 1 ??
    }

Thanks.

Upvotes: 2

Views: 6120

Answers (1)

Jakub Kania
Jakub Kania

Reputation: 16487

That's what a while loop is for, not for loop.

i <- 1
while(i <= 10)
{
  i <- i + 1 #
  flag <- ... # some code
  if (flag > 1) {
    # some code
  } 
  else{
    i <- #some arbitrary number    
  }
}

Do note however that you may end up in infinite loop if you are not careful.

Upvotes: 6

Related Questions