12.3 Summary

ds4psy: (12) Iteration

Loops are important and powerful — especially when combining them with conditional statements and your own Functions (see Chapter 11).

But when using vectors and tables as primary data structures, loops can often be replaced by alternative commands that specify a mapping between functions and data structures (e.g., the rows or columns of a table). Due to its nature as a functional programming language, R provides nifty ways to avoid loops by applying or mapping functions to various data structures.

After working through this chapter, you are able to:

  1. understand the notion of iteration in computer programming,
  2. use for loops to iterate over sequences of a known length,
  3. use while loops to iterate over sequences of an unknown length,
  4. use base R apply functions to replace some loops,
  5. use purrr map functions to replace some loops.

For more information on loops in general, see the contributed cheatsheets on Base R and Advanced R. For an overview of the map functions of purrr, take a look at the R Studio Cheat Sheet to check which commands you are now familiar with and which others you can still discover in the future:

Apply functions with **purrr** summary from [R Studio Cheat Sheets](https://www.rstudio.com/resources/cheatsheets/).

Figure 12.2: Apply functions with purrr summary from R Studio Cheat Sheets.

Let’s test our knowledge and skills on loops and applying functions to data structures by completing the following exercises.