Jump Statements in R

We use a jump statement in loops to terminate the loop at a particular iteration or to skip a particular iteration in the loop. The two most commonly used jump statements in loops are: 

Break Statement:

A break statement is a jump statement that is used to terminate the loop at a particular iteration. The program then continues with the next statement outside the loop(if any).

Example: 

R




# R Program to demonstrate the use of
# break in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
    if (i == 0)
    {
        break
    }
   print(i)
}
print("Outside Loop")


Output:

[1] 3
[1] 6
[1] 23
[1] 19
[1] Outside loop

Here the loop exits as soon as zero is encountered. 

Next Statement

It discontinues a particular iteration and jumps to the next iteration. So when next is encountered, that iteration is discarded and the condition is checked again. If true, the next iteration is executed. Hence, the next statement is used to skip a particular iteration in the loop.

Example: 

R




# R Program to demonstrate the use of
# next in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
    if (i == 0)
    {
        next
    }
    print(i)
}
print('Outside Loop')


Output: 

[1] 3
[1] 6
[1] 23
[1] 19
[1] 21
[1] Outside loop

For loop in R

For loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry-controlled loop, in this loop, the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.

Similar Reads

For loop in R Syntax:

for (var in vector) { statement(s) }...

Flowchart of For loop in R:

For loop in R...

Nested For-loop in R

...

Jump Statements in R

...

Creating Multiple Plots within for-Loop in R

...

Contact Us