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.


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 and ifelse()?

  • In the following code, what will the value of y be if x is TRUE? What if x is FALSE? What if x is NA?

    y <- if (x) 3
  • What does switch("x", x = , y = 2, z = 3) return?


  • Section 5.2 dives into the details of if, then discusses the close relatives ifelse() and switch().

  • Section 5.3 starts off by reminding you of the basic structure of the for loop in R, discusses some common pitfalls, and then talks about the related while and repeat statements.