Chapter 12 Iteration

ds4psy: (12) Iteration

The notion of iteration is an essential concept of computer programming. Basically, iteration implies doing things repeatedly. Whenever a procedure or process requires repetitions, computers really begin to shine.

Iteration with `for` loops, `apply()`, or the `map()` functions of **purrr**.

Figure 12.1: Iteration with for loops, apply(), or the map() functions of purrr.

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 to repeatedly execute 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 for and while loops here, and only briefly touch upon the base R apply (R Core Team, 2021) and the map family of functions of the purrr package (Henry & Wickham, 2020).

Together with our previous chapter on Functions (see Chapter 11), this chapter concludes our brief part on computer programming.