# Building special constructs of nested loop in for & while loops in ‘R’

By Priya Chetty on September 18, 2017

For loops are popular command as it implies that the number of iterations are fixed and are known before applying. R is preferably used for manipulating large sets of data, consisting of matrix, data frames and lists. Nested loop helps in iteration of steps in matrices. Simply put, nested for loop refers to a for loop inside a for loop.

```Syntax of nested for loop

for (var 1 in seq 1){
for (var 2 in seq 2) {
expr
}
}

```

In the above syntax, observe two loops or condition statements. Nested loops are for matrices and since matrices are multi-dimensional arrays storing data, there are two conditional statements- var 1 in seq 1 and var 2 in seq 2. There are two nested for loops in the code chunk above and thus two sets of curly braces, each with its own block and governed by its own index.

## Using nested for loops in matrix

Create a programme for nested loop, taking the instanced matrix named ‘mymat’, which represents integers in its rows and columns. Now, print the information of all rows and columns using nested for loop.

The two-dimensional array in the above figure generated the integers positioned in the rows and columns in 10 x 10 matrix.

## Using nested loop with for in data frames

Now, we will use the nested loop to generate information of restaurants in data frame restaurants_grandma (introduced earlier in Data Manipulation through Data Frames). In selecting the rows and columns in outer and inner loop respectively, the outcome consisted of the expression “the restaurant has”.

Note: The expression used in the below figure to define the outcome generated– “the restaurant has” contains certain flaws but the sole intention of the writers were to make the readers understand the function of nested loop. Hence, this article has not dealt with the the flaws, largely.

Outer loop should contain rows and inner loop should contain columns. Remember, apart from 2 sets of nested for loops, a sequence of multiplication tables can be developed with the help of array () function.

## While loop

Despite being the handiest when it comes to iteration, for loop is restricted in its usage. Further, its strength of fixing the number of iterations becomes its weakness under certain situations. For instance, a service based organization knows its customers and thus can “enlist 10 of its most important customers”, if asked. However, there comes such situations when one cannot predict the exact number of iterations in advance. For instance, while calculating the number to total visits on a website in the last two days or the number of clients living in Hyderabad.

The while loop is made of an initialization block as before, followed by a logical condition. This condition is typically expressed by the comparison between a control variable and a value, by using greater than, less than or equal to. But any expression that evaluates to a logical value, true or false, is legitimate.

As observed in the above flowchart, if the result is false, one cannot execute the loop. The program will execute the first instruction it finds after the loop block. If true, the instruction or block of instructions i1 gets executed. Note in the above flowchart, an additional instruction or block of instructions i2 is added. This serves as an update for the control variable, which alters the result of the condition at the start of the loop, but this is not necessary. Add an increment to a counter to keep trace of the number of iterations executed. The iterations cease once the condition evaluates to false. The format is while (cond) expr, where cond is the condition to test and expr is an expression.

```while (condition) {
expr
}```

## Instance of Application of While Loop

The following instance shows the usage of the while loop syntax:

The above figure states that since condition 1 (ctr <= 7) is read true by R interpreter as ctr is 1. While loop follows both the instructions, resulting the value of ctr till 7. To check if it had followed the second instruction, type ctr after the above code in the ‘R’ console and the result will be 8– as ctr = ctr + 1 (7 + 1 = 8).

Remember, to impose a condition to while loop to save it from going into infinite iterations. Without it, R would throw error about the missing expression that would provide the required true or false.

## Repeat Loop- an extension of While loop

Besides while loop, there is another type of loop-  the repeat loop, acting as an extension of the former. However, repeat loop executes the blocks of instruction i1 and i2 at least once. Adhering to other languages, one could call this loop “repeat until” to execute the instructions i1 and i2 until the condition remains false or equivalently becomes true. Flowchart of repeat loop is presented below. Note that, the diagram represents starkly opposite of while loop, with the instructions preceding the conditions.