What are the loop commands in R?
Overview
A loop in programming is a sequence of instructions that is continually repeated until a certain condition is reached. Loops continue to execute a block of code until the given condition is achieved.
Loop commands in R
In R language, there are two types of loop commands:
- The
whileloop command - The
forloop command
The while loop command
The while loop will execute a set of statements as long as the given condition is true.
Syntax of the while loop
While(expression){
statement(s)
}
The statement provided will continue to be executed in the code snippet above if the expression or condition provided is TRUE.
Example
In the code below, we want to print the values of the variable x as long as x is less than 5.
Note: The
expressionor the condition given here can be read as "as long asxis less than5"
# creating a variablex <- 1# using the while loopwhile (x < 5) {# printing the statement to be executedprint(x)x <- x + 1}
Explanation
In the example above, x has an initial value of 1 and will be incremented by 1 after each iteration of the loop. The output should produce a sequence of numbers starting from 1 to 4, and the terminating condition for the loop will be x < 5.
The
whileloop requires relevant variables to be ready. In the code above, we needed to define an indexing variable,x, which we set to1.
The for loop command
A for loop command in R is used to iterate over a sequence.
Syntax of the for loop
for(expression){
statement(s)
}
Example
In the code below, we want to print the values of x within the range 1 to 10.
for (x in 1:10) {print(x)}
In the code above, we print the values of x between the range 1 to 10 using the for loop.
We can also see that the for loop here is more like an iterator method that loops through a collection of items one at a time, which is normally seen in other programming languages as well.
Note: This is a bit different from a simple
forloop.
Summary
The only difference between for and while loop commands is that the former (for loop) does not require an indexing variable to be set beforehand while the latter (while loop) does.