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:
- understand the notion of iteration in computer programming,
forloops to iterate over sequences of a known length,
whileloops to iterate over sequences of an unknown length,
- use the
apply()family of functions of base R to replace some loops,
- 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 RStudio cheatsheet to check which commands you are now familiar with and which others you can still discover in the future:
Let’s test our knowledge and skills on loops and applying functions to data structures by completing the following exercises.