-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotes.Rmd
533 lines (296 loc) · 8.1 KB
/
notes.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
---
title: "Stat 33B - Lecture Notes 6"
date: September 27, 2020
output: pdf_document
---
Apply Function Basics
=====================
Doing the same operation repeatedly is a common pattern in programming.
Vectorization is one way, but not all functions are vectorized.
In R, the "apply functions" are another way to do something repeatedly.
The apply functions call a function on each element of a vector or list.
The `lapply()` Function
---------------------
The first and most important apply function is `lapply()`. The syntax is:
```
lapply(X, FUN, ...)
```
The function `FUN` is called once for each element of `X`, with the element as
the first argument. The `...` is for additional arguments to `FUN`, which are
held constant across all calls.
Unrealistic example:
```{r}
x = c(1, 7, 9)
lapply(x, sin)
sin(x)
```
In practice, it's clearer and more efficient to use vectorization here.
Let's use the dogs data for some realistic examples:
```{r}
dogs = readRDS("data/dogs/dogs.rds")
head(dogs)
lapply(dogs, class)
class(dogs)
str(dogs)
cols = c("weight", "height", "price")
lapply(dogs[cols], median, na.rm = TRUE)
```
`lapply()` always returns the result as a list.
"l" for **list** result.
The `sapply()` Function
---------------------
`sapply()` simplifies the result to a vector, when possible.
"s" for **simplified** result.
Examples:
```{r}
sapply(dogs[cols], median, na.rm = TRUE)
```
The `sapply()` function is useful if you are working interactively.
The Split-Apply Strategy
========================
The `split()` function splits a vector or data frame into groups based on some
other vector (usually congruent).
```{r}
x = c(1, 7, 9, 2, 5)
group = c("blue", "red", "blue", "green", "red")
split(x, group)
```
Split weight of dogs by the group column:
```{r}
dogs = readRDS("data/dogs/dogs.rds")
by_group = split(dogs, dogs$group)
```
The `split()` function is especially useful when combined with `lapply()` or
`sapply`().
```{r}
price_by_group = split(dogs$price, dogs$group)
sapply(price_by_group, mean, na.rm = TRUE)
sapply(price_by_group, sd, na.rm = TRUE)
weight_by_size = split(dogs$weight, dogs$size)
sapply(weight_by_size, mean, na.rm = TRUE)
```
This is an R idiom!
The `tapply()` Function
---------------------
The `tapply()` function is equivalent to the `split()` and `sapply()` idiom.
"t" for **table**, because `tapply()` is a generalization of the
frequency-counting function `table()`.
Examples:
```{r}
tapply(dogs$weight, dogs$size, mean, na.rm = TRUE)
# A generalization of table:
tapply(dogs$size, dogs$size, length)
table(dogs$size)
```
This strategy is important for analyzing tabular data regardless of what
programming language or packages you're using.
Even More Apply Functions
=========================
The `vapply()` Function
---------------------
`vapply()` simplifies the result to a vector of a specific data type.
"v" for **vector** (or matrix) result.
Examples:
```{r}
dogs = readRDS("data/dogs/dogs.rds")
sapply(dogs[c("weight", "height")], median, na.rm = TRUE)
vapply(dogs[c("weight", "height")], median, 5100, na.rm = TRUE)
# vapply(dogs[c("weight", "height")], median, "hi", na.rm = TRUE)
# vapply(dogs[c("weight", "height")], median, c(1, 2), na.rm = TRUE)
```
The `vapply()` function is more robust and efficient than `sapply()` because
the return type is specified.
Use `vapply()` when you write functions or other non-interactive code.
The `mapply()` and `Map()` Functions
--------------------------------
`mapply()` applies a function to multiple data arguments.
"m" for **multiple** arguments.
Examples:
```{r}
x = c(1, 2, 3, 4)
y = c(-1, 10, 20, 45)
x + y
# sum(x[1], y[1])
# sum(x[2], y[2])
mapply(sum, x, y)
# More realistic:
rep(letters[1:4], 4:1)
rep("a", 4)
rep("b", 3)
# ...
mapply(rep, letters[1:4], 4:1)
```
`mapply()` simplifies the result to a vector, when possible.
`Map()` is a wrapper for `mapply()` that never simplifies the result.
The `apply()` Function
--------------------
What if we want to compute the standard deviation of each row in a matrix?
The `apply()` function applies a function along one or more dimensions of an
array. The syntax is:
```
apply(X, MARGIN, FUN, ...)
```
The `MARGIN` is a vector of dimensions to apply the function over. 1 means
rows, 2 means columns, and so on.
For example:
```{r}
m = matrix(1:6, 2)
m
apply(m, 1, sd)
apply(m, 2, sd)
apply(m, 2, mean)
apply(m, c(1, 2), mean)
```
`apply()` returns a vector or matrix result.
`apply()` is rarely used, and when it is, it's usually for matrices.
Choosing an Apply Function
==========================
1. Is the function you want to apply vectorized?
If yes, use vectorization.
Otherwise, continue to #2.
2. Do you want to apply the function to elements or to groups?
For elements, continue to #3.
For groups, use the split-apply pattern. Use `split()`, then
continue to #3 to choose an apply function.
Note `tapply()` is equivalent to `split()` and `sapply()`.
3. Will the function return the same data type for each element?
If yes, continue to #4.
Otherwise, use `lapply()`.
4. Are you working interactively?
If yes, use `sapply()`.
Otherwise, use `vapply()`.
Other Apply Functions
---------------------
See this StackOverflow Post for a summary:
https://stackoverflow.com/a/7141669
The purrr and dplyr packages provide Tidyverse alternatives to apply functions.
Conditional Expressions
=======================
The syntax for an if-statement in R is:
```{r}
x = 20
if (x < 10) {
message("Hello")
} else {
message("Goodbye")
}
```
The `else` block is optional:
```{r}
x = -1
if (x < 2)
message("Hi")
```
Curly braces `{ }` are optional for single-line expressions:
```{r}
if (x < 2) {
message("Hi")
}
```
The condition has to be a scalar:
```{r}
if (c(TRUE, FALSE)) {
message("hello")
}
```
You can chain together if-statements:
```{r}
if (x < 4) {
message("33A")
} else if (x > 10) {
message("33B")
} else {
message("STATS")
}
```
If-statements return the value of the last expression in the evaluated block:
```{r}
output = if (x > 4) 4 else 5
output
output = if (x != 10) {
message("hi")
42
} else {
message("bye")
8
}
if (x != 10) {
message("hi")
output = 42
} else {
message("bye")
output = 8
}
```
When there's no `else` block, the value of the `else` block is `NULL`:
```{r}
y = if (FALSE) 4
```
The `switch()` function
=====================
The `switch()` function uses integer or string matching to select an expression
to evaluate.
String example:
```{r}
x = "hewfwwrw"
switch(x, hi = 45, bye = 38, hello = mean(rnorm(3)), 7)
```
Integer example:
```{r}
x = 5
switch(x, 1, 2, 3, 4, 50, median(1:3))
```
`switch()` only evaluates the selected expression.
So `switch()` is more efficient than using a list and subsetting:
```{r}
ll = list(1, 2, 3, 4, 50, median(1:3))
ll[[x]]
```
The Congruent Vectors Strategy
==============================
If-statements don't work well with vectors.
For example, suppose we want to transform a vector `x` so that:
* Negative elements are set to 0.
* Positive elements are squared.
Using an if-statement doesn't work for this:
```{r}
x = c(-4, 5, 10, -3, 2, 1)
# NO GOOD:
if (x < 0)
x = 0
```
Instead, use congruent vectors:
1. An input vector (or vectors) to use in conditions.
2. An output vector to store the results.
Use the input vector to conditionally assign elements to the output vector.
So:
```{r}
output = x
output[x < 0] = 0
output[x > 0] = x[x > 0]^2
output
```
Another example:
```{r}
y = c(4, 5, 6, 10, -1, 2)
color = c("blue", "red", "blue", "green", "red", "red")
# Say we want to:
# red -> square
# blue -> cube
# green -> 0
output = numeric(length(y))
output[color == "red"] = y[color == "red"]^2
output[color == "blue"] = y[color == "blue"]^3
output[color == "green"] = 0
output
```
The `ifelse()` Function
-----------------------
R also has a vectorized `ifelse()` function.
For example:
```{r}
x = c(-1, 10, 20, -3)
ifelse(x < 0, 0, x)
```
The `ifelse()` function is less efficient than a regular if-statement or the
congruent vectors strategy.