0

I want to set a loop to run from 1 to 10. Then from within the loop I want to change the index so to skip iterations 6 and 7, and complete the loop with iterations 8, 9 and 10.

for (i in 1:10) {
  print(i) 
  if (i == 5) {
    i <- 8
    print(i)
  }
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 5
[1] 8
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Clearly, i after my line 1 <- 8 is set by the function for to 6. Is there any way to prevent this?

3
  • 2
    R allows to use a variable twice in this case and corrects for unusual programming style. The looping variable remains unaffected by the change of i within the loop. The variable defined inside the loop is stored effectively as a separate variable. Commented Aug 31, 2015 at 6:57
  • Why not loop over only the variables you want to do something with? Or use an if(i satisifies condition){do something} construct? Commented Aug 31, 2015 at 7:10
  • 3
    Possible duplicate of this Commented Aug 31, 2015 at 7:57

3 Answers 3

5

As you're talking about skipping, the best idea is to use next on the values you wish to skip:

for (i in 1:10) {
  if (i %in% c(6,7)) {
    next
  }
  print(i) 
}

Quote from help("for"):

next halts the processing of the current iteration and advances the looping index.

Another option is to restrict the ranges your looping over like this:

for(i in c(1:5,8:10)) {
  print(i)
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it like that:

i=1
while (i<=10) {
  print(i) 
  if (i == 5) {
    i <- 8
  }else i<-i+1
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 8
[1] 9
[1] 10

Comments

0

There are two ways of doing this :

for( i in 1:10) {
    if(i!=6 && i!=7) {
        print(i)
    }
}

And, another is :

i = 1
while(i<=10) {
  print(i) 
  if(i == 5) {
    i <- i + 3
  } else {
    i <- i+1
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.