You are currently viewing Nested For Loop in R

If a for loop (inner loop) exists inside the body of the outer loop is called a nested for loop in R. In each iteration of the outer loop, the inner loop will be re-started and the inner loop must finish all of its iterations before the outer loop can continue to its next iteration.

Advertisements

The inner or outer loop can be any type, such as a while loop,  for loop, or repeat loop. For example, the outer for loop can contain an inner while loop and vice versa. Remember that the for loop is always used in combination with an object like a list, vector, or array.

Below is a simple example of a nested for loop in R.

r nested for loop
Nested for Loop in R

1. What is Nested Loop in R?

Nested loops are nothing new to programming, they have been there in pretty much all programming languages. The nested loop in R is the control statement, a loop inside the body of the other outer loop. The outer and inner loops can be any of while, for, and repeat statements.

In each iteration of the outer loop, the inner loop will be restarted, and the inner loop must finish all of its iterations before the outer loop can continue to its next iteration. In some cases, the inner loop can exit with a break statement.

Note that the outer loop can contain more than one inner loop (any number of inner loops). An inner loop can have more than one inner loop and so on without any limit.

2. Nested for Loop in R

The nested for loop in R will have a for loop inside the body of the outer for loop. The outer and inner loops are both for loops.


# nested for loop
# outer loop
for (i in c('A','B','C')){
  # inner loop
  for (j in c('X','Y')){
    # print i and j values
    print(c(i,j))
  }
}

Yields below output.

nested loop in r

Now let’s see another example of for loop using while as inner loop.


# using while inner loop
# outer loop
for (i in 1:3){
  # inner loop
  j <- 1
  while (j <= i){
    # print i and j
    print(c(i,j))
    j <- j + 1
  }
}

Yields below output.


# output
[1] 1 1
[1] 2 1
[1] 2 2
[1] 3 1
[1] 3 2
[1] 3 3

3. Break Statement in Nested Loops

The break and next statements are Jump statements in R that are used to interrupt the looping statements.

The break is used within the scope of either outer or inner loop to exit the iteration without looping through all the items in sequence.

When we use a break statement inside the inner loop, it just terminates the inner loop but not the outer loop.

The below example breaks the outer loop when i == 'C'


# nested for loop using break
# outer loop
for (i in c('A','B','C')){
  if( i == 'C')
    break
  # inner loop
  for (j in c('X','Y')){
    # print i & j
    print(c(i,j))
  }
}

# output
#[1] "A" "X"
#[1] "A" "Y"
#[1] "B" "X"
#[1] "B" "Y"

Let’s look at another example of a nested for loop in R using a break statement in an inner loop.


# nested for loop using break
# outer loop
for (i in c('A','B','C')){
  if( i == 'C')
    break
  # inner loop
  for (j in c('X','Y')){
    # print i & j
    if( j == 'Y')
      break
    print(c(i,j))
  }
}

# Output
#[1] "A" "X"
#[1] "B" "X"

4. Next Statement in Nested Loop

The next is similar to continue from other programming languages that is used to skip the rest of the iterator and jump to the next item in the sequence.

When we use a next statement inside the inner loop, it just skips the current iterations of the inner loop and continue with the next iteration.


# nested for loop using next
# outer loop
for (i in c('A','B','C')){
  # inner loop
  for (j in c('X','Y')){
    # print multiplication
    if( i == 'B' && j == 'X')
      next
    print(c(i,j))
  }
}

# output
#[1] "A" "X"
#[1] "A" "Y"
#[1] "B" "Y"
#[1] "C" "X"
#[1] "C" "Y"

5. Nested while Loop in R

The nested while loop in R will have a while loop inside the body of the outer while loop. The outer and inner loops are both while loops.


# nested while loop
# outer loop
i=1
while (i <= 3){
  # inner loop
  j <- 1
  while (j <= i){
    # print i & j
    print(c(i,j))
    j <- j + 1
  }
  i <- i + 1
}

I will leave this to you to run and explore the output.

6. Conclusion

In this article, you have learned what is nested for loop in R and how to create one. If a for loop (inner loop) exists inside the body of the outer loop is called a nested for loop. In each iteration of the outer loop, the inner loop will be re-started, The inner loop must finish all of its iterations before the outer loop can continue to its next iteration. The inner or outer loop can be any type, such as a while loop,  for loop, or repeat loop.

You can find the complete example at R GitHub examples

Related Articles

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium