R Continue for Loop

Gustavo du Mortier Jan 25, 2021
R Continue for Loop

When you have many lines of code inside a loop, and you want R to continue for the next iteration when some condition is met, you can write an if clause that evaluates the condition, and if it is true, skip everything in the loop and continue for the next iteration. That skipping is done with the next instruction.

A typical case is when you use a loop to go through a series of data elements and do some calculations on each one, leaving aside those that meet a particular condition. In the following example, we go through a vector of numbers, multiplying all of them except for those that are multiples of 5.

result <- 1
base <- 5
x <- c(7, 5, 3, 10, 8, 4, 11, 15, 6, 13)
for (num in x) {
    if (num %% base == 0) {
        next
    }
    result <- result * num
}
paste ('Result:', result)

Output:

[1] 576576

Note that the result is the multiplication of all the vector numbers except for 5, 10, and 15.

Related Article - R Loop