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.
The if
and 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 (for
, while
, and 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.
Chapter Goals
After reading this chapter, you should:
- Be able to branch the flow of execution
- Be able to repeatedly execute code with loops
Flow Control
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
. if
takes a logical value (more precisely, a logical vector of length one) and executes the next statement only if that value is TRUE
:
if
(
TRUE
)
message(
"It was true!"
)
## It was true!
if
(
FALSE
)
message(
"It wasn't true!"
)
Missing values aren’t allowed to be passed to if
; doing so throws an error:
if
(
NA
)
message(
"Who knows if it was true?" ...
Get Learning R now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.