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

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. 

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

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

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

Figure 4: Flowchart reflecting 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 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:

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

Figure 6: Flowchart reflection process of Repeat Loop

Note, set a condition  within the loop to exit with the clause break. This clause introduces to the notion of exiting or interrupting cycles within loops, as seen in the For Loop article.

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.

Sudeshna

Senior Analyst at Project Guru
Sudeshna likes to observe and pen down the goings-on in her surrounding, socially and politically. Having a Master's degree in International Relations, her interests lies in analyzing the occurrences of various countries. Previously worked as a teacher, she now holds the position of a Research Analyst in Project Guru and writes down her thoughts through various articles in the Knowledge Tank section.

Related articles

  • R software and its useful tools for handling big data R software has plenty of packages and is unique in handling big data. Therefore it can handle both the structured and unstructured data. This makes it suitable for big data analysis also.
  • Advantages of using R statistical software for predictive modelling Predictive modelling is a data driven, induction based modelling that is continuously used by big sized companies to gain useful insights into trends and risks budding in the future. The modelling on the basis of data extraction, cleansing and analysis helps in predicting the value of a […]
  • Handling text value and characters in MATLAB If the text value itself contains single quote; eg. Sam’s in the image 2 below, then three single quotes are used within the statement. Two for text and one for the apostrophe.
  • Correlation analysis using STATA Correlation analysis is conducted to examine the relationship between dependent and independent variables. There are two types of correlation analysis in STATA.
  • How to perform cross validation on a data set? Thus to assess the model, a common practice in data science is to iterate over various models and select the most appropriate model. In other words it is important to test the same model with different values of parameters.This is called the cross validation method.

Discuss

We are looking for candidates who have completed their master's degree or Ph.D. Click here to know more about our vacancies.