How to Break a for Loop in R

Jesse John Feb 15, 2024
  1. Example of a for Loop in R
  2. the break Keyword in R
  3. Use break to Terminate a Nested for Loop in R
  4. Working With the break Keyword in R
  5. Conclusion
How to Break a for Loop in R

A for loop has two peculiarities in R: it iterates over the elements of an object, and it does not return anything.

To terminate a for loop before it completes as many iterations as the number of elements in the object, we have only one option: the break keyword.

Example of a for Loop in R

We start by creating a vector (myVec) because the for loop iterates over the elements of an object. A variable (elem) in the for block holds the value of the current element of the vector.

The for loop iterates as many times as the elements in the vector.

Example Code:

myVec = c("First Name", "Last Name", "Address", "Phone", "Country")

for (elem in myVec) {
    print(elem)
}

Output:

[1] "First Name"
[1] "Last Name"
[1] "Address"
[1] "Phone"
[1] "Country"

The output displays each element of the vector on a new line, indicating the sequential iteration over the elements of myVec in the order they appear in the vector.

the break Keyword in R

The break statement stops the execution of a for loop prematurely. When certain conditions are met within the loop, the break statement is encountered, which causes an immediate exit from the loop, skipping the remaining iterations.

This mechanism is particularly useful when you want to interrupt the loop execution based on a specific condition without completing all iterations. In the examples below, we will use the break keyword at different places in two different loops to show when the loop terminates.

Example Code 1:

Exits on the third iteration before printing the updated value of the elem variable.

myVec = c("First Name", "Last Name", "Address", "Phone", "Country")

for (elem in myVec) {
    if (elem == "Address") {
        break
    }
    print(elem)
}

In this code, we have a vector named myVec containing strings. We use a for loop to iterate through each element of the vector.

Inside the loop, there’s an if statement checking if the current element is equal to "Address". If this condition is met, it executes the break statement, terminating the loop prematurely.

As a result, when the loop encounters the element "Address", it breaks out, and only the elements before "Address" are printed.

Output:

[1] "First Name"
[1] "Last Name"

The output shows that the loop stops printing elements once it reaches "Address" due to the break statement, demonstrating the early termination capability of the break keyword.

Example Code 2:

Exits on the third iteration after printing the updated value of the elem variable.

myVec = c("First Name", "Last Name", "Address", "Phone", "Country")

for (elem in myVec) {
    print(elem)
    if (elem == "Address") {
        break
    }
}

In this code, we have a vector named myVec containing strings. We use a for loop to iterate through each element of the vector.

Inside the loop, we print each element using the print() function. Additionally, there’s an if statement checking if the current element is equal to "Address".

If this condition is met, it executes the break statement, causing the loop to terminate prematurely.

Output:

[1] "First Name"
[1] "Last Name"
[1] "Address"

In the output, we can see that the loop prints all elements from the vector, and when it reaches "Address", it breaks out, and no further elements are printed.

Use break to Terminate a Nested for Loop in R

In R, we can use the break statement to terminate a nested for loop prematurely. The break statement, when encountered, exits the innermost loop in which it is placed.

This allows us to break out of both the inner and outer loops simultaneously based on a specified condition.

Example Code 1:

myVec = c("First Name", "Last Name", "Address", "Phone", "Country")
myVec2 = c("One", "Two", "Three")

for (item in myVec2) {
    for (elem in myVec) {
        cat(item, ": ", elem, "\n")
        if (item == "Two" && elem == "Address") {
            break
        }
    }
}

In this code, we have two vectors, myVec and myVec2, containing strings. We use nested for loops to iterate over elements of both vectors.

The cat function prints combinations of elements from both vectors, separated by a colon and newline. The loop includes a condition (if) that checks for the combination "Two" and "Address".

Output:

One :  First Name
One :  Last Name
One :  Address
One :  Phone
One :  Country
Two :  First Name
Two :  Last Name
Two :  Address
Three :  First Name
Three :  Last Name
Three :  Address
Three :  Phone
Three :  Country

We find that the break keyword in a nested loop only affected the execution of that loop when the if condition was met. The outer loop continued its iterations, and it happened because the condition for break involved variables from both loops.

If we use a condition from only the inner loop, it will break on each outer loop iteration. The inner loop will not get executed completely in any outer loop iteration.

Example Code 2:

myVec = c("First Name", "Last Name", "Address", "Phone", "Country")
myVec2 = c("One", "Two", "Three")

for (item in myVec2) {
    for (elem in myVec) {
        cat(item, ": ", elem, "\n")
        if (elem == "Address") {
            break
        }
    }
}

In the code, we use nested for loops to iterate over elements in two vectors, myVec and myVec2. The cat function prints combinations of elements from both vectors, separated by a colon and newline.

The inner loop contains a condition (if) that checks for the element "Address" in myVec.

Output:

One :  First Name
One :  Last Name
One :  Address
Two :  First Name
Two :  Last Name
Two :  Address
Three :  First Name
Three :  Last Name
Three :  Address

The output displays these combinations until "Address" is encountered, at which point the loop exits. We find that the break keyword in the nested loop got executed in every iteration of the outer loop because the if condition was met each time.

Finally, let us see the effect of placing the break keyword in the outer loop. We will place the keyword immediately after the nested loop in the example.

The if condition is met during the second iteration of the outer loop, but the break keyword comes after the nested for loop. So, the nested loop gets executed before the outer loop is terminated.

Example code 3:

myVec = c("First Name", "Last Name", "Address", "Phone", "Country")
myVec2 = c("One", "Two", "Three")

for (item in myVec2) {
    for (elem in myVec) {
        cat(item, ": ", elem, "\n")
    }
    if (item == "Two") {
        break
    }
}

In this code, we use nested for loops to print combinations of elements from vectors myVec and myVec2 using the cat function. The inner loop prints each combination, and the outer loop checks if the current element in myVec2 is "Two".

Output:

One :  First Name
One :  Last Name
One :  Address
One :  Phone
One :  Country
Two :  First Name
Two :  Last Name
Two :  Address
Two :  Phone
Two :  Country

In the output, we can observe that after printing combinations for "Two", the outer loop stops, and no combinations for "Three" are printed.

Working With the break Keyword in R

When using the break keyword in a for loop, we need to use our coding logic to ensure two things.

  • The break command gets executed only under the conditions we want.

  • The rest of the loop runs as we want it to.

The print() statement is one tool that can help us in this task. We can add the print() statement in the innermost loop or each loop.

Examining the output will show us the conditions under which the break command was executed.

Help With R Functions

For help with R functions or keywords in R Studio, click Help > Search R Help and type the function name or keyword in the search box (without parentheses).

Alternately, type a question mark followed by the function or keyword name at the command prompt in the R Console. For example, ?break.

Conclusion

We explored the utility of the break keyword within a for loop in R, particularly useful for prematurely terminating the loop based on specific conditions. The article provided a straightforward example of a for loop iterating over a vector, followed by an in-depth explanation of the break statement.

Two scenarios demonstrated the effective use of break within a loop, illustrating how it exits when certain conditions are met. The discussion extended to nested for loops, showing how break can terminate both inner and outer loops simultaneously.

The article recommended using print() statements to understand the conditions triggering the break command. For additional assistance, users were guided to leverage built-in help features in R Studio.

Author: Jesse John
Jesse John avatar Jesse John avatar

Jesse is passionate about data analysis and visualization. He uses the R statistical programming language for all aspects of his work.