Introduction to Loops
Let's begin learning all about loops in R.
We'll cover the following
What are Loops?
There may be a situation when we need to execute a block of code multiple times.
In general, statements are executed sequentially, which means one after another. The first statement executed first, followed by the second, and so on. However, now we want certain statements to be executed again and again given that a condition is satisfied.
Printing Numbers Example
Suppose we are given a task to print numbers from to . We can use print()
statements for this:
print(1)print(2)print(3)print(4)print(5)
Now assume we are asked to extend our code and this time print numbers from to :
print(1)print(2)print(3)print(4)print(5)print(6)print(7)print(8)print(9)print(10)
But as we are going to increase the number, it will eventually get too tedious to use the print function again and again. R, like most other programming languages, provides a construct whereby we can instruct the compiler to repeat certain statement(s) a certain number of times or as long as a certain condition is true. This construct is called a loop. For example:
myNumber <- 1while (myNumber <= 10){print(myNumber)myNumber = myNumber + 1;}
Let’s look at an illustration that represents how the code executed:
According to this illustration, the compiler checks if the condition evaluates to true, then executes the statement, and keep on doing this until the condition becomes false. If the condition returns false, then exit the loop. The portion enclosed in the red line is the block of code that is called the loop.