Chapter 8. Flow Control and Loops
In R, as with other languages, there are many instances where we might want to conditionally execute code, or to repeatedly execute similar code.
switch functions of R should be familiar if you have programmed in other languages, though the fact that they are functions may be new to you. Vectorized conditional execution via the
ifelse function is also an R speciality.
We’ll look at all of these in this chapter, as well as the three simplest loops (
repeat), which again should be reasonably familiar from other languages. Due to the vectorized nature of R, and some more aesthetic alternatives, these loops are less commonly used in R than you may expect.
After reading this chapter, you should:
- Be able to branch the flow of execution
- Be able to repeatedly execute code with loops
There are many occasions where you don’t just want to execute one statement after another: you need to control the flow of execution. Typically this means that you only want to execute some code if a condition is fulfilled.
if and else
The simplest form of flow control is conditional execution using
if takes a logical value (more precisely, a logical vector of length one) and executes the next statement only if that value is
"It was true!"
## It was true!
"It wasn't true!"
Missing values aren’t allowed to be passed to
if; doing so throws an error:
"Who knows if it was true?" ...