1

If condition occurs in the inner for loop I want to break the inner and next the outer.

I could create a flag in the inner before the break statement and then evaluate in the outer, this is a silly example:

for (i in 1:3) {
  NEXT <- FALSE
  for (j in 1:3) {
    if (j==2 && i==2) { 
      NEXT <- TRUE
      break
    }
  }
  
  if (NEXT) next
  cat("\n", i, " ... some i stuff ...")
}

Is there an elegant way to do it? Something like:

for (i in 1:3) {
  for (j in 1:3) {
    if (j==2 && i==2) {
      break
      # next (outer)
    }
  }
  cat("\n", i, " ... some i stuff ...")
}

There a similar/duplicate question but I think it doesn't answer's mine, because in the question's outer loop it does nothing after the inner loop.

How to jump to next top level loop?

nurasaki
  • 89
  • 1
  • 9

2 Answers2

0

A quick fix could be something like:

for(i in 1:3){
 for(j in 1:3){
  if(i == 2 && j == 2){
   i <- 3 # can be ignored if you don't want i value changed
   j <- 3 # this will kick it out of the j for loop
   } else {
   ...code...
 }
 cat ....
}

Obviously, it's not robust but seems to solve your problem.

EDIT:

Per your comment, perhaps you're looking for:

for(i in 1:3){
 cat.ready <- TRUE
 for(j in 1:3){
  if(i == 2 && j == 2){
   j <- 3 # this will kick it out of the j for loop
   cat.ready <- FALSE
   } else {
    ...code...
 }
 if(cat.ready == TRUE){
  cat(...)
 } else {
 cat.ready <- TRUE
}

This then will remove you from executing code and also from producing a cat() if i and j are both 2 and will reset the condition after that exception has been handled.

I'm sure there is a more elegant solution, however.

Justin Cocco
  • 392
  • 1
  • 6
  • I think this doesn't work, the desired response is: `1 ... some i stuff ... 2 ... some i stuff ...` – nurasaki Dec 20 '20 at 11:21
  • Perhaps I don't understand then. I think this would work, no? It would still process the code as long as `i` and `j` aren't both `2` and after its done processing `j` it would move down to the `cat()` which is nested under the `i` argument. – Justin Cocco Dec 20 '20 at 12:52
0

Why not invert the problem and only execute the inner loop if j!=2 && i!=2?

for (i in 1:3) {
  for (j in 1:3) {
       cat("\n\ni=",i, " and j=",j )
       if (j!=2 | i!=2 )
       # will be executed unless j is 2 and i is 2
       {
       cat("\n", j, " ... some j stuff ...")
              }
  }
  cat("\n", i, " ... some i stuff ...")
}

If I am misunderstanding and you want to not execute the combination of j=2/i=2 and j=3/i=2 adjust accordingly:

for (i in 1:3) {
  for (j in 1:3) {
       cat("\n\ni=",i, " and j=",j )
       if (j!=2 | i!=2 & i!=3)
       # will be executed unless j is 2 and i is 2 or j is 3 and i is 2
       {
       cat("\n", j, " ... some j stuff ...")
              }
  }
  cat("\n", i, " ... some i stuff ...")
}
Mario Niepel
  • 1,095
  • 4
  • 19