12.4 Summary

ds4psy: (12) Iteration

Loops are important and can be very 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 the apply() family of functions of base R to replace some loops,
  5. use the map() family of functions of purrr 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 Posit cheatsheets 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 Posit cheatsheets.

Figure 12.7: Apply functions with purrr summary from Posit cheatsheets.

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