-
Notifications
You must be signed in to change notification settings - Fork 230
/
iteration.Rmd
1005 lines (797 loc) · 26.7 KB
/
iteration.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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Iteration {#iteration .r4ds-section}
## Introduction {#introduction-14 .r4ds-section}
The **microbenchmark** package is used for timing code.
```{r message=FALSE,cache=FALSE}
library("tidyverse")
library("stringr")
library("microbenchmark")
```
<div class="alert alert-warning hints-alert">
The `map()` function appears in both the purrr and maps packages. See the
"Prerequisites" section of the [Introduction](https://r4ds.had.co.nz/data-visualisation.html#introduction-1).
If you see errors like the following, you are using the wrong `map()` function.
```rconsole
> map(c(TRUE, FALSE, TRUE), ~ !.)
Error: $ operator is invalid for atomic vectors
> map(-2:2, rnorm, n = 5)
Error in map(-2:2, rnorm, n = 5) :
argument 3 matches multiple formal arguments
```
You can check the package in which a function is defined using the `environment()` function:
```{r}
environment(map)
```
The result should include `namespace:purrr` if `map()` is coming from the purrr package.
To explicitly reference the package to get a function from, use the colon operator `::`.
For example,
```{r}
purrr::map(c(TRUE, FALSE, TRUE), ~ !.)
```
</div>
## For loops {#for-loops .r4ds-section}
### Exercise 21.2.1 {.unnumbered .exercise data-number="21.2.1"}
<div class="question">
Write for-loops to:
1. Compute the mean of every column in `mtcars`.
1. Determine the type of each column in `nycflights13::flights`.
1. Compute the number of unique values in each column of `iris`.
1. Generate 10 random normals for each of $\mu$ = -10, 0, 10, and 100.
</div>
<div class="answer">
The answers for each part are below.
1. To compute the mean of every column in `mtcars`.
```{r}
output <- vector("double", ncol(mtcars))
names(output) <- names(mtcars)
for (i in names(mtcars)) {
output[i] <- mean(mtcars[[i]])
}
output
```
1. Determine the type of each column in `nycflights13::flights`.
```{r}
output <- vector("list", ncol(nycflights13::flights))
names(output) <- names(nycflights13::flights)
for (i in names(nycflights13::flights)) {
output[[i]] <- class(nycflights13::flights[[i]])
}
output
```
I used a `list`, not a character vector, since the class of an object can have multiple values.
For example, the class of the `time_hour` column is `r class(nycflights13::flights$time_hour)`.
1. To compute the number of unique values in each column of the `iris` dataset.
```{r}
data("iris")
iris_uniq <- vector("double", ncol(iris))
names(iris_uniq) <- names(iris)
for (i in names(iris)) {
iris_uniq[i] <- n_distinct(iris[[i]])
}
iris_uniq
```
1. To generate 10 random normals for each of $\mu$ = -10, 0, 10, and 100.
```{r}
# number to draw
n <- 10
# values of the mean
mu <- c(-10, 0, 10, 100)
normals <- vector("list", length(mu))
for (i in seq_along(normals)) {
normals[[i]] <- rnorm(n, mean = mu[i])
}
normals
```
However, we don't need a for loop for this since `rnorm()` recycle the `mean` argument.
```{r}
matrix(rnorm(n * length(mu), mean = mu), ncol = n)
```
</div>
### Exercise 21.2.2 {.unnumbered .exercise data-number="21.2.2"}
<div class="question">
Eliminate the for loop in each of the following examples by taking advantage of an existing function that works with vectors:
</div>
<div class="answer">
```{r}
out <- ""
for (x in letters) {
out <- str_c(out, x)
}
out
```
Since `str_c()` already works with vectors, use `str_c()` with the `collapse` argument to return a single string.
```{r}
str_c(letters, collapse = "")
```
For this I'm going to rename the variable `sd` to something different because `sd` is the name of the function we want to use.
```{r}
x <- sample(100)
sd. <- 0
for (i in seq_along(x)) {
sd. <- sd. + (x[i] - mean(x))^2
}
sd. <- sqrt(sd. / (length(x) - 1))
sd.
```
We could simply use the `sd` function.
```{r}
sd(x)
```
Or if there was a need to use the equation (e.g. for pedagogical reasons), then
the functions `mean()` and `sum()` already work with vectors:
```{r}
sqrt(sum((x - mean(x))^2) / (length(x) - 1))
```
```{r}
x <- runif(100)
out <- vector("numeric", length(x))
out[1] <- x[1]
for (i in 2:length(x)) {
out[i] <- out[i - 1] + x[i]
}
out
```
The code above is calculating a cumulative sum. Use the function `cumsum()`
```{r}
all.equal(cumsum(x), out)
```
</div>
### Exercise 21.2.3 {.unnumbered .exercise data-number="21.2.3"}
<div class="question">
Combine your function writing and for loop skills:
1. Write a for loop that `prints()` the lyrics to the children's song "Alice the camel".
1. Convert the nursery rhyme "ten in the bed" to a function.
Generalize it to any number of people in any sleeping structure.
1. Convert the song "99 bottles of beer on the wall" to a function.
Generalize to any number of any vessel containing any liquid on surface.
</div>
<div class="answer">
The answers to each part follow.
1. The lyrics for [Alice the Camel](https://www.kididdles.com/lyrics/a012.html) are:
> Alice the camel has five humps. \
> Alice the camel has five humps. \
> Alice the camel has five humps. \
> So go, Alice, go.
This verse is repeated, each time with one fewer hump,
until there are no humps.
The last verse, with no humps, is:
> Alice the camel has no humps. \
> Alice the camel has no humps. \
> Alice the camel has no humps. \
> Now Alice is a horse.
We'll iterate from five to no humps, and print out a different last line if there are no humps.
```{r}
humps <- c("five", "four", "three", "two", "one", "no")
for (i in humps) {
cat(str_c("Alice the camel has ", rep(i, 3), " humps.",
collapse = "\n"
), "\n")
if (i == "no") {
cat("Now Alice is a horse.\n")
} else {
cat("So go, Alice, go.\n")
}
cat("\n")
}
```
1. The lyrics for [Ten in the Bed](https://www.kididdles.com/lyrics/t003.html) are:
> Here we go! \
> There were ten in the bed \
> and the little one said, \
> “Roll over, roll over.” \
> So they all rolled over and one fell out.
This verse is repeated, each time with one fewer in the bed, until there is one left.
That last verse is:
> One!
> There was one in the bed \
> and the little one said, \
> “I’m lonely...”
```{r}
numbers <- c(
"ten", "nine", "eight", "seven", "six", "five",
"four", "three", "two", "one"
)
for (i in numbers) {
cat(str_c("There were ", i, " in the bed\n"))
cat("and the little one said\n")
if (i == "one") {
cat("I'm lonely...")
} else {
cat("Roll over, roll over\n")
cat("So they all rolled over and one fell out.\n")
}
cat("\n")
}
```
1. The lyrics of [Ninety-Nine Bottles of Beer on the Wall](https://en.wikipedia.org/wiki/99_Bottles_of_Beer) are
> 99 bottles of beer on the wall, 99 bottles of beer. \
> Take one down, pass it around, 98 bottles of beer on the wall
This verse is repeated, each time with one few bottle, until
there are no more bottles of beer. The last verse is
> No more bottles of beer on the wall, no more bottles of beer. \
> We've taken them down and passed them around; now we're drunk and passed out!
For the bottles of beer, I define a helper function to correctly print the number of bottles.
```{r}
bottles <- function(n) {
if (n > 1) {
str_c(n, " bottles")
} else if (n == 1) {
"1 bottle"
} else {
"no more bottles"
}
}
beer_bottles <- function(total_bottles) {
# print each lyric
for (current_bottles in seq(total_bottles, 0)) {
# first line
cat(str_to_sentence(str_c(bottles(current_bottles), " of beer on the wall, ", bottles(current_bottles), " of beer.\n")))
# second line
if (current_bottles > 0) {
cat(str_c(
"Take one down and pass it around, ", bottles(current_bottles - 1),
" of beer on the wall.\n"
))
} else {
cat(str_c("Go to the store and buy some more, ", bottles(total_bottles), " of beer on the wall.\n")) }
cat("\n")
}
}
beer_bottles(3)
```
</div>
#### Exercise 21.2.4 {.unnumbered .exercise data-number="21.2.4"}
<div class="question">
It's common to see for loops that don't preallocate the output and instead increase the length of a vector at each step:
```{r, eval = FALSE}
output <- vector("integer", 0)
for (i in seq_along(x)) {
output <- c(output, lengths(x[[i]]))
}
output
```
How does this affect performance?
Design and execute an experiment.
</div>
<div class="answer">
In order to compare these two approaches, I'll define two functions:
`add_to_vector` will append to a vector, like the example in the question,
and `add_to_vector_2` which pre-allocates a vector.
```{r}
add_to_vector <- function(n) {
output <- vector("integer", 0)
for (i in seq_len(n)) {
output <- c(output, i)
}
output
}
```
```{r}
add_to_vector_2 <- function(n) {
output <- vector("integer", n)
for (i in seq_len(n)) {
output[[i]] <- i
}
output
}
```
I'll use the package microbenchmark to run these functions several times and compare the time it takes.
The package microbenchmark contains utilities for benchmarking R expressions.
In particular, the `microbenchmark()` function will run an R expression a number of times and time it.
```{r}
timings <- microbenchmark(add_to_vector(10000), add_to_vector_2(10000), times = 10)
timings
```
```{r include=FALSE}
timings_summary <- summary(timings)
d <- round(timings_summary[1, "median"] / timings_summary[2, "median"])
```
In this example, appending to a vector takes `r round(d)` times longer than pre-allocating the vector.
You may get different answers, but the longer the vector and the larger the objects, the more that pre-allocation will outperform appending.
</div>
## For loop variations {#for-loop-variations .r4ds-section}
### Exercise 21.3.1 {.unnumbered .exercise data-number="21.3.1"}
<div class="question">
Imagine you have a directory full of CSV files that you want to read in.
You have their paths in a vector,
`files <- dir("data/", pattern = "\\.csv$", full.names = TRUE)`, and now
want to read each one with `read_csv()`. Write the for loop that will
load them into a single data frame.
</div>
<div class="answer">
```{r}
files <- dir("data/", pattern = "\\.csv$", full.names = TRUE)
files
```
Since, the number of files is known, pre-allocate a list with a length equal to the number of files.
```{r}
df_list <- vector("list", length(files))
```
Then, read each file into a data frame, and assign it to an element in that list.
The result is a list of data frames.
```{r}
for (i in seq_along(files)) {
df_list[[i]] <- read_csv(files[[i]])
}
```
```{r}
print(df_list)
```
Finally, use use `bind_rows()` to combine the list of data frames into a single data frame.
```{r}
df <- bind_rows(df_list)
```
```{r}
print(df)
```
Alternatively, I could have pre-allocated a list with the names of the files.
```{r}
df2_list <- vector("list", length(files))
names(df2_list) <- files
for (fname in files) {
df2_list[[fname]] <- read_csv(fname)
}
df2 <- bind_rows(df2_list)
```
</div>
### Exercise 21.3.2 {.unnumbered .exercise data-number="21.3.2"}
<div class="question">
What happens if you use `for (nm in names(x))` and `x` has no names?
What if only some of the elements are named?
What if the names are not unique?
</div>
<div class="answer">
Let's try it out and see what happens.
When there are no names for the vector, it does not run the code in the loop.
In other words, it runs zero iterations of the loop.
```{r}
x <- c(11, 12, 13)
print(names(x))
for (nm in names(x)) {
print(nm)
print(x[[nm]])
}
```
Note that the length of `NULL` is zero:
```{r}
length(NULL)
```
If there only some names, then we get an error for trying to access an element without a name.
```{r}
x <- c(a = 11, 12, c = 13)
names(x)
```
```{r error = TRUE}
for (nm in names(x)) {
print(nm)
print(x[[nm]])
}
```
Finally, if the vector contains duplicate names, then `x[[nm]]` returns the *first* element with that name.
```{r}
x <- c(a = 11, a = 12, c = 13)
names(x)
```
```{r}
for (nm in names(x)) {
print(nm)
print(x[[nm]])
}
```
</div>
### Exercise 21.3.3 {.unnumbered .exercise data-number="21.3.3"}
<div class="question">
Write a function that prints the mean of each numeric column in a data frame, along with its name.
For example, `show_mean(iris)` would print:
```{r eval=FALSE}
show_mean(iris)
# > Sepal.Length: 5.84
# > Sepal.Width: 3.06
# > Petal.Length: 3.76
# > Petal.Width: 1.20
```
Extra challenge: what function did I use to make sure that the numbers lined up nicely, even though the variable names had different lengths?
</div>
<div class="answer">
There may be other functions to do this, but I'll use `str_pad()`, and `str_length()` to ensure that the space given to the variable names is the same.
I messed around with the options to `format()` until I got two digits.
```{r}
show_mean <- function(df, digits = 2) {
# Get max length of all variable names in the dataset
maxstr <- max(str_length(names(df)))
for (nm in names(df)) {
if (is.numeric(df[[nm]])) {
cat(
str_c(str_pad(str_c(nm, ":"), maxstr + 1L, side = "right"),
format(mean(df[[nm]]), digits = digits, nsmall = digits),
sep = " "
),
"\n"
)
}
}
}
show_mean(iris)
```
</div>
### Exercise 21.3.4 {.unnumbered .exercise data-number="21.3.4"}
<div class="question">
What does this code do?
How does it work?
```{r}
trans <- list(
disp = function(x) x * 0.0163871,
am = function(x) {
factor(x, labels = c("auto", "manual"))
}
)
```
```{r eval=FALSE}
for (var in names(trans)) {
mtcars[[var]] <- trans[[var]](mtcars[[var]])
}
```
</div>
<div class="answer">
This code mutates the `disp` and `am` columns:
- `disp` is multiplied by 0.0163871
- `am` is replaced by a factor variable.
The code works by looping over a named list of functions.
It calls the named function in the list on the column of `mtcars` with the same name, and replaces the values of that column.
This is a function.
```{r eval=FALSE}
trans[["disp"]]
```
This applies the function to the column of `mtcars` with the same name
```{r eval=FALSE}
trans[["disp"]](mtcars[["disp"]])
```
</div>
## For loops vs. functionals {#for-loops-vs.functionals .r4ds-section}
### Exercise 21.4.1 {.unnumbered .exercise data-number="21.4.1"}
<div class="question">
Read the documentation for `apply()`.
In the 2nd case, what two for-loops does it generalize.
</div>
<div class="answer">
For an object with two-dimensions, such as a matrix or data frame, `apply()` replaces looping over the rows or columns of a matrix or data-frame.
The `apply()` function is used like `apply(X, MARGIN, FUN, ...)`, where `X` is a matrix or array, `FUN` is a function to apply, and `...` are additional arguments passed to `FUN`.
When `MARGIN = 1`, then the function is applied to each row.
For example, the following example calculates the row means of a matrix.
```{r}
X <- matrix(rnorm(15), nrow = 5)
X
```
```{r}
apply(X, 1, mean)
```
That is equivalent to this for-loop.
```{r}
X_row_means <- vector("numeric", length = nrow(X))
for (i in seq_len(nrow(X))) {
X_row_means[[i]] <- mean(X[i, ])
}
X_row_means
```
```{r}
X <- matrix(rnorm(15), nrow = 5)
X
```
When `MARGIN = 2`, `apply()` is equivalent to a for-loop looping over columns.
```{r}
apply(X, 2, mean)
```
```{r}
X_col_means <- vector("numeric", length = ncol(X))
for (i in seq_len(ncol(X))) {
X_col_means[[i]] <- mean(X[, i])
}
X_col_means
```
</div>
### Exercise 21.4.2 {.unnumbered .exercise data-number="21.4.2"}
<div class="question">
Adapt `col_summary()` so that it only applies to numeric columns.
You might want to start with an `is_numeric()` function that returns a logical vector that has a `TRUE` corresponding to each numeric column.
</div>
<div class="answer">
The original `col_summary()` function is
```{r}
col_summary <- function(df, fun) {
out <- vector("double", length(df))
for (i in seq_along(df)) {
out[i] <- fun(df[[i]])
}
out
}
```
The adapted version adds extra logic to only apply the function to numeric columns.
```{r}
col_summary2 <- function(df, fun) {
# create an empty vector which will store whether each
# column is numeric
numeric_cols <- vector("logical", length(df))
# test whether each column is numeric
for (i in seq_along(df)) {
numeric_cols[[i]] <- is.numeric(df[[i]])
}
# find the indexes of the numeric columns
idxs <- which(numeric_cols)
# find the number of numeric columns
n <- sum(numeric_cols)
# create a vector to hold the results
out <- vector("double", n)
# apply the function only to numeric vectors
for (i in seq_along(idxs)) {
out[[i]] <- fun(df[[idxs[[i]]]])
}
# name the vector
names(out) <- names(df)[idxs]
out
}
```
Let's test that `col_summary2()` works by creating a small data frame with
some numeric and non-numeric columns.
```{r}
df <- tibble(
X1 = c(1, 2, 3),
X2 = c("A", "B", "C"),
X3 = c(0, -1, 5),
X4 = c(TRUE, FALSE, TRUE)
)
col_summary2(df, mean)
```
As expected, it only calculates the mean of the numeric columns, `X1` and `X3`.
Let's test that it works with another function.
```{r}
col_summary2(df, median)
```
</div>
## The map functions {#the-map-functions .r4ds-section}
### Exercise 21.5.1 {.unnumbered .exercise data-number="21.5.1"}
<div class="question">
Write code that uses one of the map functions to:
1. Compute the mean of every column in `mtcars`.
1. Determine the type of each column in `nycflights13::flights`.
1. Compute the number of unique values in each column of `iris`.
1. Generate 10 random normals for each of $\mu = -10$, $0$, $10$, and $100$.
</div>
<div class="answer">
1. To calculate the mean of every column in `mtcars`, apply the function
`mean()` to each column, and use `map_dbl`, since the results are numeric.
```{r}
map_dbl(mtcars, mean)
```
1. To calculate the type of every column in `nycflights13::flights` apply
the function `typeof()`, discussed in the section on [Vector basics](https://r4ds.had.co.nz/vectors.html#vector-basics),
and use `map_chr()`, since the results are character.
```{r}
map_chr(nycflights13::flights, typeof)
```
1. The function `n_distinct()` calculates the number of unique values
in a vector.
```{r}
map_int(iris, n_distinct)
```
The `map_int()` function is used since `length()` returns an integer.
However, the `map_dbl()` function will also work.
```{r results='hide'}
map_dbl(iris, n_distinct)
```
An alternative to the `n_distinct()` function is the expression, `length(unique(...))`.
The `n_distinct()` function is more concise and faster, but `length(unique(...))` provides an example of using anonymous functions with map functions.
An anonymous function can be written using the standard R syntax for a function:
```{r}
map_int(iris, function(x) length(unique(x)))
```
Additionally, map functions accept one-sided formulas as a more concise alternative to specify an anonymous function:
```{r}
map_int(iris, ~length(unique(.x)))
```
In this case, the anonymous function accepts one argument, which is referenced by `.x` in the expression `length(unique(.x))`.
1. To generate 10 random normals for each of $\mu = -10$, $0$, $10$, and $100$:
The result is a list of numeric vectors.
```{r}
map(c(-10, 0, 10, 100), ~rnorm(n = 10, mean = .))
```
Since a single call of `rnorm()` returns a numeric vector with a length greater
than one we cannot use `map_dbl`, which requires the function to return a numeric
vector that is only length one (see [Exercise 21.5.4](#exercise-21.5.4)).
The map functions pass any additional arguments to the function being called.
</div>
### Exercise 21.5.2 {.unnumbered .exercise data-number="21.5.2"}
<div class="question">
How can you create a single vector that for each column in a data frame indicates whether or not it's a factor?
</div>
<div class="answer">
The function `is.factor()` indicates whether a vector is a factor.
```{r}
is.factor(diamonds$color)
```
Checking all columns in a data frame is a job for a `map_*()` function.
Since the result of `is.factor()` is logical, we will use `map_lgl()` to apply `is.factor()` to the columns of the data frame.
```{r}
map_lgl(diamonds, is.factor)
```
</div>
### Exercise 21.5.3 {.unnumbered .exercise data-number="21.5.3"}
<div class="question">
What happens when you use the map functions on vectors that aren't lists?
What does `map(1:5, runif)` do?
Why?
</div>
<div class="answer">
Map functions work with any vectors, not just lists.
As with lists, the map functions will apply the function to each element of the vector.
In the following examples, the inputs to `map()` are atomic vectors (logical, character, integer, double).
```{r}
map(c(TRUE, FALSE, TRUE), ~ !.)
map(c("Hello", "World"), str_to_upper)
map(1:5, ~ rnorm(.))
map(c(-0.5, 0, 1), ~ rnorm(1, mean = .))
```
It is important to be aware that while the input of `map()` can be any vector, the output is always a list.
```{r}
map(1:5, runif)
```
This expression is equivalent to running the following.
```{r}
list(
runif(1),
runif(2),
runif(3),
runif(4),
runif(5)
)
```
The `map()` function loops through the numbers 1 to 5.
For each value, it calls the `runif()` with that number as the first argument, which is the number of sample to draw.
The result is a length five list with numeric vectors of sizes one through five, each with random samples from a uniform distribution.
Note that although input to `map()` was an integer vector, the return value was a list.
</div>
### Exercise 21.5.4 {.unnumbered .exercise data-number="21.5.4"}
<div class="question">
What does `map(-2:2, rnorm, n = 5)` do?
Why?
What does `map_dbl(-2:2, rnorm, n = 5)` do?
Why?
</div>
<div class="answer">
Consider the first expression.
```{r}
map(-2:2, rnorm, n = 5)
```
This expression takes samples of size five from five normal distributions, with means of (-2, -1, 0, 1, and 2), but the same standard deviation (1).
It returns a list with each element a numeric vectors of length 5.
However, if instead, we use `map_dbl()`, the expression raises an error.
```{r error = TRUE}
map_dbl(-2:2, rnorm, n = 5)
```
This is because the `map_dbl()` function requires the function it applies to each element to return a numeric vector of length one.
If the function returns either a non-numeric vector or a numeric vector with a length greater than one, `map_dbl()` will raise an error.
The reason for this strictness is that `map_dbl()` guarantees that it will return a numeric vector of the *same length* as its input vector.
This concept applies to the other `map_*()` functions.
The function `map_chr()` requires that the function always return a *character* vector of length one;
`map_int()` requires that the function always return an *integer* vector of length one;
`map_lgl()` requires that the function always return an *logical* vector of length one.
Use the `map()` function if the function will return values of varying types or lengths.
To return a numeric vector, use `flatten_dbl()` to coerce the list returned by `map()` to a numeric vector.
```{r}
map(-2:2, rnorm, n = 5) %>%
flatten_dbl()
```
</div>
### Exercise 21.5.5 {.unnumbered .exercise data-number="21.5.5"}
<div class="question">
Rewrite `map(x, function(df) lm(mpg ~ wt, data = df))` to eliminate the anonymous function.
</div>
<div class="answer">
This code in this question does not run, so I will use the following code.
```{r}
x <- split(mtcars, mtcars$cyl)
map(x, function(df) lm(mpg ~ wt, data = df))
```
We can eliminate the use of an anonymous function using the `~` shortcut.
```{r}
map(x, ~ lm(mpg ~ wt, data = .))
```
Though not the intent of this question, the other way to eliminate anonymous function is to create a named one.
```{r}
run_reg <- function(df) {
lm(mpg ~ wt, data = df)
}
map(x, run_reg)
```
</div>
## Dealing with failure {#dealing-with-failure .r4ds-section}
`r no_exercises()`
## Mapping over multiple arguments {#mapping-over-multiple-arguments .r4ds-section}
`r no_exercises()`
## Walk {#walk .r4ds-section}
`r no_exercises()`
## Other patterns of for loops {#other-patterns-of-for-loops .r4ds-section}
### Exercise 21.9.1 {.unnumbered .exercise data-number="21.9.1"}
<div class="question">
Implement your own version of `every()` using a for loop.
Compare it with `purrr::every()`.
What does purrr's version do that your version doesn't?
</div>
<div class="answer">
```{r}
# Use ... to pass arguments to the function
every2 <- function(.x, .p, ...) {
for (i in .x) {
if (!.p(i, ...)) {
# If any is FALSE we know not all of then were TRUE
return(FALSE)
}
}
# if nothing was FALSE, then it is TRUE
TRUE
}
every2(1:3, function(x) {
x > 1
})
every2(1:3, function(x) {
x > 0
})
```
The function `purrr::every()` does fancy things with the predicate function argument `.p`, like taking a logical vector instead of a function, or being able to test part of a string if the elements of `.x` are lists.
</div>
### Exercise 21.9.2 {.unnumbered .exercise data-number="21.9.2"}
<div class="question">
Create an enhanced `col_summary()` that applies a summary function to every numeric column in a data frame.
</div>
<div class="answer">
I will use `map` to apply the function to all the columns, and `keep` to only select numeric columns.
```{r}
col_sum2 <- function(df, f, ...) {
map(keep(df, is.numeric), f, ...)
}
```
```{r}
col_sum2(iris, mean)
```
</div>
### Exercise 21.9.3 {.unnumbered .exercise data-number="21.9.3"}
<div class="question">
A possible base R equivalent of `col_summary()` is:
```{r}
col_sum3 <- function(df, f) {
is_num <- sapply(df, is.numeric)
df_num <- df[, is_num]
sapply(df_num, f)
}
```
But it has a number of bugs as illustrated with the following inputs:
```{r, eval=FALSE}
df <- tibble(
x = 1:3,
y = 3:1,
z = c("a", "b", "c")
)
# OK
col_sum3(df, mean)
# Has problems: don't always return numeric vector
col_sum3(df[1:2], mean)
col_sum3(df[1], mean)
col_sum3(df[0], mean)
```
What causes these bugs?
</div>
<div class="answer">
The cause of these bugs is the behavior of `sapply()`.
The `sapply()` function does not guarantee the type of vector it returns, and will returns different types of vectors depending on its inputs.
If no columns are selected, instead of returning an empty numeric vector, it returns an empty list.
This causes an error since we can't use a list with `[`.
```{r}
sapply(df[0], is.numeric)
```
```{r}
sapply(df[1], is.numeric)
```
```{r}
sapply(df[1:2], is.numeric)