The notion of “iteration” is an essential concept of computer programming. Basically, iteration is a method for tackling tasks that have the general form “for each \(X\), do \(Y\)”. Thus, implies solving some task \(Y\) repeatedly (\(X\) times). Whenever a procedure or process requires repetitions, computers really begin to shine.
The traditional way to handle iteration is by repeating code in loops. When the number of required iterations is known in advance, we can use
for loops to repeat some code for the desired number of times. In cases for which the number of iterations cannot be known beforehand, a
while loop provides a general way for repeatedly executing some code.
As R is a functional programming language, it provides additional ways of applying functions repeatedly to data structures.
As this book focuses on the essentials, we will primarily discuss
while loops here, and only briefly touch upon the base R
apply (R Core Team, 2022) and the
map family of functions of the purrr package (Henry & Wickham, 2020).