honeybadger
honeybadger

Reputation: 1575

How to break from only certain loops in R

I am currently running three for loops in R and when I hit a particular condition, I want to break from the lower 2 loops alone, but continue in the top-level loop.

Here is an example that breaks only from the lowest level loop, i.e. 'b' in this case. I want to break from both the 'a' and 'b' loops and return to the loop 'i':

for (i in 1:10) {
  for (a in 1:10) {
    for(b in 1:10) {

      if (b == 7) { break }

    }
  }
}

Upvotes: 3

Views: 1515

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269596

1) function Place the inner two loops in a function and return from it like this:

inner <- function(i) {
  for (a in 1:3) {
    for(b in 1:3) {
      cat("i,a,b:", i, a, b, "\n")
      if (b == 2) return()
    }
  }
}

for (i in 1:3) {
  inner(i)
}

giving:

i,a,b: 1 1 1 
i,a,b: 1 1 2 
i,a,b: 2 1 1 
i,a,b: 2 1 2 
i,a,b: 3 1 1 
i,a,b: 3 1 2 

2) second break Another possibility is to perform a second test in the a loop:

for (i in 1:3) {
  for (a in 1:3) {
    for(b in 1:3) {
      cat("i,a,b:", i, a, b, "\n")
      if (b == 2) break
    }
    if (b < 3) break
  }
}

giving:

i,a,b: 1 1 1 
i,a,b: 1 1 2 
i,a,b: 2 1 1 
i,a,b: 2 1 2 
i,a,b: 3 1 1 
i,a,b: 3 1 2 

Upvotes: 2

HolgerBarlt
HolgerBarlt

Reputation: 317

maybe you should think of replacing the most inner for Loop by an while Loop

for(i in 1:10){
  for(j in 1:10){
    k <- 1
    while(k < 7){
      k <- k + 1
      cat(sprintf("hallo %d %d %d\n",i,j,k))
    }
  } 
}

Upvotes: 1

Related Questions