13 Loops
13.1 Loops
Loops are a fundamental component of (procedural) programming.
There are two main types of loops:
- conditional loops are executed as long as a defined condition holds true
- construct
while
- construct
repeat
- construct
- deterministic loops are executed a pre-determined number of times
- construct
for
- construct
13.2 While
The while construct can be defined using the while
reserved word, followed by the conditional statement between simple brackets, and a code block. The instructions in the code block are re-executed as long as the result of the evaluation of the conditional statement is TRUE
.
current_value <- 0
while (current_value < 3) {
cat("Current value is", current_value, "\n")
current_value <- current_value + 1
}
## Current value is 0
## Current value is 1
## Current value is 2
13.3 For
The for construct can be defined using the for
reserved word, followed by the definition of an iterator. The iterator is a variable which is temporarily assigned with the current element of a vector, as the construct iterates through all elements of the list. This definition is followed by a code block, whose instructions are re-executed once for each element of the vector.
cities <- c("Derby", "Leicester", "Lincoln", "Nottingham")
for (city in cities) {
cat("Do you live in", city, "?\n")
}
## Do you live in Derby ?
## Do you live in Leicester ?
## Do you live in Lincoln ?
## Do you live in Nottingham ?
13.4 For
It is common practice to create a vector of integers on the spot in order to execute a certain sequence of steps a pre-defined number of times.
## This is exectuion number 1 :
## See you later!
## This is exectuion number 2 :
## See you later!
## This is exectuion number 3 :
## See you later!
13.5 Loops with conditional statements
## [1] 3 2 1 0
## 3
## 2
## 1
## Go!