-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path09-intro-to-loops.Rmd
438 lines (313 loc) · 8.08 KB
/
09-intro-to-loops.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
---
title: "Introduction to loops"
subtitle: "Stat 133"
author: "Gaston Sanchez"
output: github_document
fontsize: 11pt
urlcolor: blue
---
> ### Learning Objectives
>
> - Why do you need loops?
> - Get to know the For loop
> - Get to know the While loop
> - Get to know the Repeat loop
```{r setup, include=FALSE}
knitr::opts_chunk$set(error = TRUE)
```
------
## About Loops
- Many times we need to perform a procedure several times
- We perform the same operation several times as long as some condition
is fulfilled
- For this purpose we use loops
- The main idea is that of __iteration__
- R provides three basic paradigms: `for`, `repeat`, `while`
## Motivation example
Consider a numeric vector with prices of five items:
```{r}
prices <- c(2.50, 2.95, 3.45, 3.25)
prices
```
### Printing prices "manually"
Say you are interested in printing each price individually. You can manually
display them one by one, by typing the same command several times:
```{r print_prices, eval = FALSE}
cat("Price 1 is", prices[1])
cat("Price 2 is", prices[2])
cat("Price 3 is", prices[3])
cat("Price 4 is", prices[4])
```
```{r print_prices, echo=FALSE}
```
### Printing prices with a `for` loop
Or you can use a loop structure in which you tell the computer to display the
prices a given number of times, but using one command instead of typing it
various times:
```{r}
for (i in 1:4) {
cat("Price", i, "is", prices[i], "\n")
}
```
Let's make it less simple by creating a vector of prices with the names of
the associated coffees:
```{r}
coffee_prices <- c(
expresso = 2.50,
latte = 2.95,
mocha = 3.45,
cappuccino = 3.25)
coffee_prices
```
Without using a loop, you can display, via `cat()`, the prices one-by-one;
(this, of course, involves a lot of repetition)
```{r print_coffee, eval = FALSE}
cat("Expresso has a price of", coffee_prices[1])
cat("Latte has a price of", coffee_prices[2])
cat("Mocha has a price of", coffee_prices[3])
cat("Capuccino has a price of", coffee_prices[4])
```
```{r print_coffee, echo = FALSE}
```
### Printing coffee prices with a `for` loop
```{r}
for (i in 1:4) {
cat(names(coffee_prices)[i], "has a price of",
prices[i], "\n")
}
```
-----
## For Loops
- Often we want to repeatedly carry out some computation a __fixed__ number of times.
- For instance, repeat an operation for each element of a vector.
- In R this can be done with a __`for`__ loop.
- `for` loops are used when __we know exactly how many times__ we want the code to repeat
The anatomy of a `for` loop is as follows:
```{r eval = FALSE}
for (iterator in times) {
do_something
}
```
`for()` takes an __iterator__ variable and a vector of __times__ to iterate
through.
```{r}
value <- 2
for (i in 1:5) {
value <- value * 2
print(value)
}
```
The vector of _times_ does NOT have to be a numeric vector; it can be __any__ vector
```{r}
value <- 2
times <- c('one', 'two', 'three', 'four')
for (i in times) {
value <- value * 2
print(value)
}
```
However, if the _iterator_ is used inside the loop in a numerical computation, then the vector of _times_ will almost always be a numeric vector:
```{r}
set.seed(4321)
numbers <- rnorm(5)
for (h in 1:length(numbers)) {
if (numbers[h] < 0) {
value <- sqrt(-numbers[h])
} else {
value <- sqrt(numbers[h])
}
print(value)
}
```
### For Loops and Next statement
Sometimes we need to skip a loop iteration if a given condition is met, this can be done with a next statement
```{r eval=FALSE}
for (iterator in times) {
expr1
expr2
if (condition) {
next
}
expr3
expr4
}
```
Example:
```{r}
x <- 2
for (i in 1:5) {
y <- x * i
if (y == 8) {
next
}
print(y)
}
```
### Nested Loops
It is common to have nested loops
```{r eval = FALSE}
for (iterator1 in times1) {
for (iterator2 in times2) {
expr1
expr2
...
}
}
```
Example: Nested loops
```{r}
# some matrix
A <- matrix(1:12, nrow = 3, ncol = 4)
A
```
Example: Nested Loops
```{r}
# reciprocal of values less than 6
for (i in 1:nrow(A)) {
for (j in 1:ncol(A)) {
if (A[i,j] < 6) A[i,j] <- 1 / A[i,j]
}
}
A
```
-----
## About `for` Loops and Vectorized Computations
- R loops have a bad reputation for being slow.
- Experienced users will tell you: "tend to avoid `for` loops in R" (me included).
- It is not really that the loops are slow; the slowness has more to do with the way R handles the _boxing and unboxing_ of data objects, which may be a bit inefficient.
- R provides a family of functions that are usually more efficient than loops
(i.e. `apply()` functions).
- For this course, especially if you have NO programming experience, you should ignore any advice about avoiding loops in R.
- You should learn how to write loops, and understand how they work; every programming language provides some type of loop structure.
- In practice, many (programming) problems can be tackled using some loop structure.
- When using R, you may need to start solving a problem using a loop. Once you solved it, try to see if you can find a vectorized alternative.
- It takes practice and experience to find alternative solutions to `for` loops.
- There are cases when using `for` loops is not that bad.
-----
## Repeat Loop
`repeat` executes the same code over and over until a stop condition is met:
```{r eval=FALSE}
repeat {
# keep
# doing
# something
if (stop_condition) {
break
}
}
```
The `break` statement stops the loops. If you enter an infinite loop, you can
manually break it by pressing the `ESC` key.
```{r}
value <- 2
repeat {
value <- value * 2
print(value)
if (value >= 40) {
break
}
}
```
To skip a current iteration, use `next`
```{r}
value <- 2
repeat {
value <- value * 2
print(value)
if (value == 16) {
value <- value * 2
next
}
if (value > 80) break
}
```
## While Loops
It can also be useful to repeat a computation until a condition is false.
A `while` loop provides this form of control flow.
```{r eval=FALSE}
while (condition) {
# keep
# doing
# something
# until
# condition is FALSE
}
```
### About while loops
- `while` loops are backward `repeat` loops
- `while` checks first and then attempts to execute
- computations are carried out for as long as the condition is true
- the loop stops when the condition is FALSE
- If you enter an infinite loop, break it by pressing `ESC` key
```{r}
value <- 2
while (value < 40) {
value <- value * 2
print(value)
}
```
-----
## Loops: `for`, `while`, `repeat`
Let's see one last example of a `for` loop, and how to achieve the same task
with `while` and `repeat` loops.
Say you have a vector `x <- c(2, 4, 6, 8, 10)`, and the goal is to obtain the
sum of the elements in `x`; in other words get `sum(x)` but using loops.
```{r}
# using a for loop
x <- c(2, 4, 6, 8, 10)
# initialize output
sumx <- 0
for (i in seq_along(x)) {
print(paste('iteration:'), i)
sumx <- sumx + x[i]
print(paste('sum =', sumx))
}
sumx
```
Now let's do it with a while loop
```{r}
# initialize output
sumx <- 0
# initialize counter
i <- 1
# while loop
while (i <= length(x)) {
print(paste('iteration:', i))
sumx <- sumx + x[i]
print(paste('sum =', sumx))
i <- i + 1
}
sumx
```
And finally with a `repeat` loop:
```{r}
# initialize output
sumx <- 0
# initialize counter
i <- 1
# repeat loop (visualizing iterations)
repeat {
print(paste('iteration:', i))
sumx <- sumx + x[i]
print(paste('sum =', sumx))
i <- i + 1
if (i > length(x)) {
break
}
}
sumx
```
-----
## Repeat, While, For
- If you don't know the number of times something will be done, you can use
either `repeat` or `while`
- `while` evaluates the condition at the beginning
- `repeat` executes operations until a stop condition is met
- If you know the number of times that something will be done, use `for`
- `for` needs an _iterator_ and a vector of _times_
### Questions
- What happens if you pass `NA` as a condition to `if()`?
- What happens if you pass `NA` as a condition to `ifelse()`?
- What types of values can be passed as the first argument to `switch()`?
- How do you stop a `repeat` loop executing?
- How do you jump to next iteration of a loop?