Building special constructs of nested loops 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 is fixed and is known before applying. R is preferably used for manipulating large sets of data, consisting of matrices, data frames and lists. A nested loop helps in the iteration of steps in matrices. Simply put, a nested for-loop refers to a for loop inside a for loop. 

Figure 1: Flowchart reflecting the process of Nested ‘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 conditional 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 a nested for loop.

Figure 1: Using nested Loops in multi-dimensional Arrays (matrix)
Figure 2: Using nested Loops in multi-dimensional Arrays (matrix)

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

Using nested loop with for-loop in data frames

Now, we will use the nested loop to generate information about restaurants in the data frame restaurants_grandma. In selecting the rows and columns in the 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 was to make the readers understand the function of the nested loop.

Figure 2: Using nested loop in data frames
Figure 3: Using nested loop in data frames

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 of 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.

Flowchart reflecting a process of While Loop
Figure 4: Flowchart reflecting a process of While Loop

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 track 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
}

An instance of the application of While loop

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

Figure 3: Using while loop in vector
Figure 5: Using while loop in vector

The above figure states that since condition 1 (ctr <= 7) is read true by the R interpreter as ctr is 1. While loop follows both the instructions, resulting in 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).

TIP

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

Repeat Loop, an extension of While loop

Besides the while loop, there is another type of loop, the repeat loop, acting as an extension of the former. However, the repeat loop executes the blocks of instructions 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. A flowchart of the repeat loop is presented below. Note that, the diagram represents starkly opposite of the while loop, with the instructions preceding the conditions.

Flowchart reflection process of Repeat Loop
Figure 6: Flowchart reflection process of Repeat Loop
NOTE

Set a condition within the loop to exit with the clause break. This clause introduces the notion of exiting or interrupting cycles within loops, as seen in for loops.

Following building the understanding of loops, the module will proceed to introduce functions, which form an extremely important concept in almost every programming language, including R.

Discuss