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 base R
applyfunctions to replace some loops,
- use purrr
mapfunctions 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:
Let’s test our knowledge and skills on loops and applying functions to data structures by completing the following exercises.