1. For loop—iterates over a sequence the number of times equal to its length (unless the statements break
and/or next
are used) and performs the same set of operations on each item of that sequence. This is the most common type of loops. The syntax of a for loop in R is the following:
for (variable in sequence) {
operations
}
Powered By
2. While loop—performs the same set of operations until a predefined logical condition (or several logical conditions) is met—unless the statements break
and/or next
are used. Unlike for loops, we don’t know in advance the number of iterations a while loop is going to execute. Before running a while loop, we need to assign a variable (or several variables) and then update its value inside the loop body at each iteration. The syntax of a while loop in R is the following:
variable assignment
while (logical condition) {
operations
variable update
}
Powered By
3. Repeat loop—repeatedly performs the same set of operations until a predefined break condition (or several break conditions) is met. To introduce such a condition, a repeat loop has to contain an if-statement code block, which, in turn, has to include the break
statement in its body. Like while loops, we don’t know in advance the number of iterations a repeat loop is going to execute. The syntax of a repeat loop in R is the following:
repeat {
operations
if(break condition) {
break
}
}
Leave a Reply