For Loop and Nested For Loop in R

For loop in R:

In this section we will have a look at how you can write a basic for loop and nested for loop in R. It is aimed at beginners.

Syntax of simple for loop in R:

for(i in 1:n)
{
statement
}

Example of simple for loop in R

# for loop in R
for(i in 1:5)
{
print (i^2)
}

Output

[1] 1

[1] 4

[1] 9

[1] 16

[1] 25

 

Syntax of Nested for loop in R:

for(i in 1:n)
{
for(j in 1:n)
{
statement
}
}

The placing of one loop inside the body of another loop is called nesting.  When you “nest” two loops, the outer loop takes control of the number of complete repetitions of the inner loop. Thus inner loop is executed N- times for every execution of Outer loop.

Example: Nested for loop in R

# R nested for loop

for(i in 1:5)
{
for(j in 1:2)
{
print(i*j);
}
}

Output

[1] 1

[1] 2

[1] 2

[1] 4

[1] 3

[1] 6

[1] 4

[1] 8

[1] 5

[1] 10

 

Next and Break Statement:

Break Statement in R for loops:

break statement is used inside a loop (repeat,for,while) to stop the iterations and flow the control outside of the loop.

# R for loop with break statement

x <- 1:5
for (i in x) {
    if (i == 3){
        break
    }
    print(i)
}

Output

[1] 1

[1] 2

The Use of “next” in R for Loop

“next” discontinues a particular iteration and jumps to the next cycle. In fact, it jumps to the evaluation of the condition holding the current loop.

Example:

# R for loop with next statement

x <- 1:5
for (i in x) {
 if (i == 2){
 next
 }
 print(i)
}

Output:

[1] 1

[1] 3

[1] 4

[1] 5

previous-small for loop in Rnext_small for loop in R

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts