forked from hadley/adv-r
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Control-flow.Rmd
390 lines (285 loc) · 10.3 KB
/
Control-flow.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# Control flow
```{r, include = FALSE}
source("common.R")
```
## 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 \@ref(conditions), 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 \@ref(control-flow-answers).
* 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`?
```{r, eval = FALSE}
y <- if (x) 3
```
* What does `switch("x", x = , y = 2, z = 3)` return?
### Outline {-}
* Section \@ref(choices) dives into the details of `if`, then discusses
the close relatives `ifelse()` and `switch()`.
* Section \@ref(loops) 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.
## Choices
\indexc{if}
The basic form of an if statement in R is as follows:
```{r, eval = FALSE}
if (condition) true_action
if (condition) true_action else false_action
```
If `condition` is `TRUE`, `true_action` is evaluated; if `condition` is `FALSE`, the optional `false_action` is evaluated.
Typically the actions are compound statements contained within `{`:
```{r}
grade <- function(x) {
if (x > 90) {
"A"
} else if (x > 80) {
"B"
} else if (x > 50) {
"C"
} else {
"F"
}
}
```
`if` returns a value so that you can assign the results:
```{r}
x1 <- if (TRUE) 1 else 2
x2 <- if (FALSE) 1 else 2
c(x1, x2)
```
(I recommend assigning the results of an `if` statement only when the entire expression fits on one line; otherwise it tends to be hard to read.)
When you use the single argument form without an else statement, `if` invisibly (Section \@ref(invisible)) returns `NULL` if the condition is `FALSE`. Since functions like `c()` and `paste()` drop `NULL` inputs, this allows for a compact expression of certain idioms:
```{r}
greet <- function(name, birthday = FALSE) {
paste0(
"Hi ", name,
if (birthday) " and HAPPY BIRTHDAY"
)
}
greet("Maria", FALSE)
greet("Jaime", TRUE)
```
### Invalid inputs
The `condition` should evaluate to a single `TRUE` or `FALSE`. Most other inputs will generate an error:
```{r, error = TRUE}
if ("x") 1
if (logical()) 1
if (NA) 1
```
The exception is a logical vector of length greater than 1, which generates a warning:
```{r, include = FALSE}
Sys.setenv("_R_CHECK_LENGTH_1_CONDITION_" = "false")
```
```{r}
if (c(TRUE, FALSE)) 1
```
In R 3.5.0 and greater, thanks to [Henrik Bengtsson](https://github.com/HenrikBengtsson/Wishlist-for-R/issues/38), you can turn this into an error by setting an environment variable:
```{r, error = TRUE}
Sys.setenv("_R_CHECK_LENGTH_1_CONDITION_" = "true")
if (c(TRUE, FALSE)) 1
```
I think this is good practice as it reveals a clear mistake that you might otherwise miss if it were only shown as a warning.
### Vectorised if
\indexc{ifelse()}
Given that `if` only works with a single `TRUE` or `FALSE`, you might wonder what to do if you have a vector of logical values. Handling vectors of values is the job of `ifelse()`: a vectorised function with `test`, `yes`, and `no` vectors (that will be recycled to the same length):
```{r}
x <- 1:10
ifelse(x %% 5 == 0, "XXX", as.character(x))
ifelse(x %% 2 == 0, "even", "odd")
```
Note that missing values will be propagated into the output.
I recommend using `ifelse()` only when the `yes` and `no` vectors are the same type as it is otherwise hard to predict the output type. See <https://vctrs.r-lib.org/articles/stability.html#ifelse> for additional discussion.
Another vectorised equivalent is the more general `dplyr::case_when()`. It uses a special syntax to allow any number of condition-vector pairs:
```{r}
dplyr::case_when(
x %% 35 == 0 ~ "fizz buzz",
x %% 5 == 0 ~ "fizz",
x %% 7 == 0 ~ "buzz",
is.na(x) ~ "???",
TRUE ~ as.character(x)
)
```
### `switch()` statement {#switch}
\indexc{switch()}
Closely related to `if` is the `switch()`-statement. It's a compact, special purpose equivalent that lets you replace code like:
```{r}
x_option <- function(x) {
if (x == "a") {
"option 1"
} else if (x == "b") {
"option 2"
} else if (x == "c") {
"option 3"
} else {
stop("Invalid `x` value")
}
}
```
with the more succinct:
```{r}
x_option <- function(x) {
switch(x,
a = "option 1",
b = "option 2",
c = "option 3",
stop("Invalid `x` value")
)
}
```
The last component of a `switch()` should always throw an error, otherwise unmatched inputs will invisibly return `NULL`:
```{r}
(switch("c", a = 1, b = 2))
```
If multiple inputs have the same output, you can leave the right hand side of `=` empty and the input will "fall through" to the next value. This mimics the behaviour of C's `switch` statement:
```{r}
legs <- function(x) {
switch(x,
cow = ,
horse = ,
dog = 4,
human = ,
chicken = 2,
plant = 0,
stop("Unknown input")
)
}
legs("cow")
legs("dog")
```
It is also possible to use `switch()` with a numeric `x`, but is harder to read, and has undesirable failure modes if `x` is a not a whole number. I recommend using `switch()` only with character inputs.
### Exercises
1. What type of vector does each of the following calls to `ifelse()`
return?
```{r, eval = FALSE}
ifelse(TRUE, 1, "no")
ifelse(FALSE, 1, "no")
ifelse(NA, 1, "no")
```
Read the documentation and write down the rules in your own words.
1. Why does the following code work?
```{r}
x <- 1:10
if (length(x)) "not empty" else "empty"
x <- numeric()
if (length(x)) "not empty" else "empty"
```
## Loops
\index{loops}
\index{loops!for@\texttt{for}}
\indexc{for}
`for` loops are used to iterate over items in a vector. They have the following basic form:
```{r, eval = FALSE}
for (item in vector) perform_action
```
For each item in `vector`, `perform_action` is called once; updating the value of `item` each time.
```{r}
for (i in 1:3) {
print(i)
}
```
(When iterating over a vector of indices, it's conventional to use very short variable names like `i`, `j`, or `k`.)
N.B.: `for` assigns the `item` to the current environment, overwriting any existing variable with the same name:
```{r}
i <- 100
for (i in 1:3) {}
i
```
\indexc{next}
\indexc{break}
There are two ways to terminate a `for` loop early:
* `next` exits the current iteration.
* `break` exits the entire `for` loop.
```{r}
for (i in 1:10) {
if (i < 3)
next
print(i)
if (i >= 5)
break
}
```
### Common pitfalls
\index{loops!common pitfalls}
There are three common pitfalls to watch out for when using `for`. First, if you're generating data, make sure to preallocate the output container. Otherwise the loop will be very slow; see Sections \@ref(memory-profiling) and \@ref(avoid-copies) for more details. The `vector()` function is helpful here.
```{r}
means <- c(1, 50, 20)
out <- vector("list", length(means))
for (i in 1:length(means)) {
out[[i]] <- rnorm(10, means[[i]])
}
```
Next, beware of iterating over `1:length(x)`, which will fail in unhelpful ways if `x` has length 0:
```{r, error = TRUE}
means <- c()
out <- vector("list", length(means))
for (i in 1:length(means)) {
out[[i]] <- rnorm(10, means[[i]])
}
```
This occurs because `:` works with both increasing and decreasing sequences:
```{r}
1:length(means)
```
Use `seq_along(x)` instead. It always returns a value the same length as `x`:
```{r}
seq_along(means)
out <- vector("list", length(means))
for (i in seq_along(means)) {
out[[i]] <- rnorm(10, means[[i]])
}
```
Finally, you might encounter problems when iterating over S3 vectors, as loops typically strip the attributes:
```{r}
xs <- as.Date(c("2020-01-01", "2010-01-01"))
for (x in xs) {
print(x)
}
```
Work around this by calling `[[` yourself:
```{r}
for (i in seq_along(xs)) {
print(xs[[i]])
}
```
### Related tools {#for-family}
\indexc{while}
\indexc{repeat}
`for` loops are useful if you know in advance the set of values that you want to iterate over. If you don't know, there are two related tools with more flexible specifications:
* `while(condition) action`: performs `action` while `condition` is `TRUE`.
* `repeat(action)`: repeats `action` forever (i.e. until it encounters `break`).
R does not have an equivalent to the `do {action} while (condition)` syntax found in other languages.
You can rewrite any `for` loop to use `while` instead, and you can rewrite any `while` loop to use `repeat`, but the converses are not true. That means `while` is more flexible than `for`, and `repeat` is more flexible than `while`. It's good practice, however, to use the least-flexible solution to a problem, so you should use `for` wherever possible.
Generally speaking you shouldn't need to use `for` loops for data analysis tasks, as `map()` and `apply()` already provide less flexible solutions to most problems. You'll learn more in Chapter \@ref(functionals).
### Exercises
1. Why does this code succeed without errors or warnings?
```{r, results = FALSE}
x <- numeric()
out <- vector("list", length(x))
for (i in 1:length(x)) {
out[i] <- x[i] ^ 2
}
out
```
1. When the following code is evaluated, what can you say about the
vector being iterated?
```{r}
xs <- c(1, 2, 3)
for (x in xs) {
xs <- c(xs, x * 2)
}
xs
```
1. What does the following code tell you about when the index is updated?
```{r}
for (i in 1:3) {
i <- i * 2
print(i)
}
```
## Quiz answers {#control-flow-answers}
* `if` works with scalars; `ifelse()` works with vectors.
* When `x` is `TRUE`, `y` will be `3`; when `FALSE`, `y` will be `NULL`;
when `NA` the if statement will throw an error.
* This `switch()` statement makes use of fall-through so it will return 2.
See details in Section \@ref(switch).