8 Doing things conditionally: Control structures

 

This chapter covers

  • Looping over sections of code
  • Conditionally evaluating code
  • Best practices to balance speed and readability

You saw in chapter 6 that you can conditionally select elements from data structures, but sometimes you only want to do (or not do) something based on some condition, or do something many times with slightly different conditions. There may be many steps you want to conditionally perform, so you need a way to only do things sometimes (or many times). You can use several approaches to do this in R, so let’s look at the most common and the most useful, as well as some other ways these tasks can be accomplished.

8.1 Looping

So far, you’ve evaluated code in a very linear manner, one line after another in a series of steps. This works fine as long as each step is a unique operation. Often, though, you want to repeat an operation several times (maybe a few times, maybe a large number of times). This comes up most frequently when you want to perform some operation on each row of a data.frame one at a time. That usage flies in the face of the vectorized nature of R and should really be discouraged.

We’ll still go through how to construct code that way, but you’ll greatly benefit by thinking “vectorization” whenever you feel the urge to write code that performs a loop. To return that notion to the front of your mind, let’s review what you learned in section 5.2.2.

8.1.1 Vectorization

8.1.2 Tidy repetition: Looping with purrr

8.1.3 for loops

8.2 Wider and narrower loop scope

8.2.1 while loops

8.3 Conditional evaluation

8.3.1 if conditions

8.3.2 ifelse conditions

8.4 Try it yourself

Terminology

Summary

sitemap