Question: I would like to stop the loop when my if condition becomes true and continue to the next lines of my code. When I run this, I get an error that the subscript i in blocks[[i]] is out of bounds. Any ideas?

```
for(i in 1:length(blocks)){
  if(length(blocks[[i]]) == 0){
    path <- path[ -i , -i]

    modes = rep("A", nrow(path))
    blocks[[i]] = NULL
  }
}

```

NOTE: I have read the help for loops, next, stop and break

Answer: 
If I understand you correctly, you want to loop while a condition is true and exit the loop when the condition become false. So you should be using the `while` control-flow operator, not `for`.

```
i <- 1
while(i<=length(blocks) & length(blocks[[i]])!=0){
    i <- i+1
}

# check that we exited the loop because there was a zero
# and not because we went through all the blocks
if(i != length(blocks+1)) {
    path <- path[ -i , -i]
    modes = rep("A", nrow(path))
    blocks[[i]] = NULL
}
# rest of your code

```

But there's really no need for loop here.

```
# apply 'length' to every element of the list blocks 
# returns a vector containing all the lengths
all_length <- sapply(blocks, FUN=length)

# check that there is at least one zero
if(any(all_length==0)) {
    # find the indexes of the zeros in 'all_length'
    zero_length_ind <- which(all_length==0)

    # this is the index of the first zero
    i <- min(zero_length_ind)
}

```

I don't know what you want to do but if your plan is to treat all the 'i' sequentially, you may actually want to work with `zero_length_ind` and treat all your zeros at once.

For example if you want to remove all the values in `path` corresponding to zero length in `blocks`, you should directly do:

```
path <- path[-zero_length_ind,-zero_length_ind]

```

(Note that if there is no zero length element in blocks, then `zero_length_ind` will be `integer(0)` (that is, an empty integer vector) and you can't use it to index `path`. This might save you some debugging time.)
Use the [STOP](https://stat.ethz.ch/R-manual/R-devel/library/base/html/stop.html) command, the code below should work 

```
    for(i in 1:length(blocks)){
        if(length(blocks[[i]]) == 0){
          path <- path[ -i , -i]

          modes = rep("A", nrow(path))
          blocks[[i]] = NULL
    `     stop("Outside bounds")

        }

      }

```