5.1 Introduction
There are two primary tools of control flow: choices and loops. Choices, like if
statements and switch()
calls, allow you to run different code depending on the input. Loops, like for
and while
, allow you to repeatedly run code, typically with changing options. I’d expect that you’re already familiar with the basics of these functions so I’ll briefly cover some technical details and then introduce some useful, but lesser known, features.
The condition system (messages, warnings, and errors), which you’ll learn about in Chapter 8, also provides non-local control flow.
Quiz
Want to skip this chapter? Go for it, if you can answer the questions below. Find the answers at the end of the chapter in Section 5.4.
What is the difference between
if
andifelse()
?In the following code, what will the value of
y
be ifx
isTRUE
? What ifx
isFALSE
? What ifx
isNA
?if (x) 3 y <-
What does
switch("x", x = , y = 2, z = 3)
return?