-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08-functional-programming.html
2105 lines (2038 loc) · 168 KB
/
08-functional-programming.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="generator" content="quarto-1.3.450">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Stat 331/531 Statistical Computing with R - 8 Functional Programming</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
/* CSS for citations */
div.csl-bib-body { }
div.csl-entry {
clear: both;
}
.hanging-indent div.csl-entry {
margin-left:2em;
text-indent:-2em;
}
div.csl-left-margin {
min-width:2em;
float:left;
}
div.csl-right-inline {
margin-left:2em;
padding-left:1em;
}
div.csl-indent {
margin-left: 2em;
}</style>
<script src="site_libs/quarto-nav/quarto-nav.js"></script>
<script src="site_libs/quarto-nav/headroom.min.js"></script>
<script src="site_libs/clipboard/clipboard.min.js"></script>
<script src="site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="site_libs/quarto-search/fuse.min.js"></script>
<script src="site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="./">
<link href="./09-statistical-modeling-and-simulation.html" rel="next">
<link href="./07-functions.html" rel="prev">
<script src="site_libs/quarto-html/quarto.js"></script>
<script src="site_libs/quarto-html/popper.min.js"></script>
<script src="site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="site_libs/quarto-html/anchor.min.js"></script>
<link href="site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="site_libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" class="quarto-color-scheme" id="quarto-text-highlighting-styles">
<link href="site_libs/quarto-html/quarto-syntax-highlighting-dark.css" rel="prefetch" class="quarto-color-scheme quarto-color-alternate" id="quarto-text-highlighting-styles">
<script src="site_libs/bootstrap/bootstrap.min.js"></script>
<link href="site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="site_libs/bootstrap/bootstrap.min.css" rel="stylesheet" class="quarto-color-scheme" id="quarto-bootstrap" data-mode="light">
<link href="site_libs/bootstrap/bootstrap-dark.min.css" rel="prefetch" class="quarto-color-scheme quarto-color-alternate" id="quarto-bootstrap" data-mode="dark">
<link href="site_libs/quarto-contrib/line-highlight-1.0.0/line-highlight.css" rel="stylesheet"><script id="quarto-search-options" type="application/json">{
"location": "sidebar",
"copy-button": false,
"collapse-after": 3,
"panel-placement": "start",
"type": "textbox",
"limit": 20,
"language": {
"search-no-results-text": "No results",
"search-matching-documents-text": "matching documents",
"search-copy-link-title": "Copy link to search",
"search-hide-matches-text": "Hide additional matches",
"search-more-match-text": "more match in this document",
"search-more-matches-text": "more matches in this document",
"search-clear-button-title": "Clear",
"search-detached-cancel-button-title": "Cancel",
"search-submit-button-title": "Submit",
"search-label": "Search"
}
}</script><script src="site_libs/kePrint-0.0.1/kePrint.js"></script><link href="site_libs/lightable-0.0.1/lightable.css" rel="stylesheet">
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script><script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js" type="text/javascript"></script><link rel="stylesheet" href="style.css">
</head>
<body class="nav-sidebar floating slimcontent">
<div id="quarto-search-results"></div>
<header id="quarto-header" class="headroom fixed-top"><nav class="quarto-secondary-nav"><div class="container-fluid d-flex">
<button type="button" class="quarto-btn-toggle btn" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar,#quarto-sidebar-glass" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
<i class="bi bi-layout-text-sidebar-reverse"></i>
</button>
<nav class="quarto-page-breadcrumbs" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="./08-functional-programming.html"><span class="chapter-number">8</span> <span class="chapter-title">Functional Programming</span></a></li></ol></nav>
<a class="flex-grow-1" role="button" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar,#quarto-sidebar-glass" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
</a>
<button type="button" class="btn quarto-search-button" aria-label="" onclick="window.quartoOpenSearch();">
<i class="bi bi-search"></i>
</button>
</div>
</nav></header><!-- content --><div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
<nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal sidebar-navigation floating overflow-auto"><div class="pt-lg-2 mt-2 text-left sidebar-header">
<div class="sidebar-title mb-0 py-0">
<a href="./">Stat 331/531 Statistical Computing with R</a>
<div class="sidebar-tools-main tools-wide">
<a href="https://github.com/earobinson95/stat331-calpoly-text" rel="" title="Source Code" class="quarto-navigation-tool px-1" aria-label="Source Code"><i class="bi bi-github"></i></a>
<div class="dropdown">
<a href="" title="Share" id="quarto-navigation-tool-dropdown-0" class="quarto-navigation-tool dropdown-toggle px-1" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Share"><i class="bi bi-share"></i></a>
<ul class="dropdown-menu" aria-labelledby="quarto-navigation-tool-dropdown-0">
<li>
<a class="dropdown-item sidebar-tools-main-item" href="https://twitter.com/intent/tweet?url=%7Curl%7C">
<i class="bi bi-bi-twitter pe-1"></i>
Twitter
</a>
</li>
<li>
<a class="dropdown-item sidebar-tools-main-item" href="https://www.facebook.com/sharer/sharer.php?u=%7Curl%7C">
<i class="bi bi-bi-facebook pe-1"></i>
Facebook
</a>
</li>
<li>
<a class="dropdown-item sidebar-tools-main-item" href="https://www.linkedin.com/sharing/share-offsite/?url=%7Curl%7C">
<i class="bi bi-bi-linkedin pe-1"></i>
LinkedIn
</a>
</li>
</ul>
</div>
<a href="" class="quarto-color-scheme-toggle quarto-navigation-tool px-1" onclick="window.quartoToggleColorScheme(); return false;" title="Toggle dark mode"><i class="bi"></i></a>
</div>
</div>
</div>
<div class="mt-2 flex-shrink-0 align-items-center">
<div class="sidebar-search">
<div id="quarto-search" class="" title="Search"></div>
</div>
</div>
<div class="sidebar-menu-container">
<ul class="list-unstyled mt-1">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./index.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">Preface</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./00-prereading.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">Pre-reading</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./01-introduction.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">1</span> <span class="chapter-title">Introduction</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./02-tidy-data-and-basics-of-graphics.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">2</span> <span class="chapter-title">Tidy Data & Basics of Graphics</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./03-data-cleaning-and-manipulation.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">3</span> <span class="chapter-title">Data Cleaning and Manipulation</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./04-data-joins-and-transformations.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">4</span> <span class="chapter-title">Data Joins and Transformations</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./05-special-data-types.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">5</span> <span class="chapter-title">Special Data Types</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./06-version-control.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">6</span> <span class="chapter-title">Version Control</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./07-functions.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">7</span> <span class="chapter-title">Writing Functions</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./08-functional-programming.html" class="sidebar-item-text sidebar-link active">
<span class="menu-text"><span class="chapter-number">8</span> <span class="chapter-title">Functional Programming</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./09-statistical-modeling-and-simulation.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">9</span> <span class="chapter-title">Regression & Simulating Distributions</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./10-predictive-checks.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">10</span> <span class="chapter-title">Predictive Checks</span></span></a>
</div>
</li>
</ul>
</div>
</nav><div id="quarto-sidebar-glass" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar,#quarto-sidebar-glass"></div>
<!-- margin-sidebar -->
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<nav id="TOC" role="doc-toc" class="toc-active"><h2 id="toc-title">Table of contents</h2>
<ul>
<li><a href="#ch8-objectives" id="toc-ch8-objectives" class="nav-link active" data-scroll-target="#ch8-objectives">Objectives</a></li>
<li><a href="#ch8-checkins" id="toc-ch8-checkins" class="nav-link" data-scroll-target="#ch8-checkins">Check-ins</a></li>
<li>
<a href="#introduction-to-iteration" id="toc-introduction-to-iteration" class="nav-link" data-scroll-target="#introduction-to-iteration"><span class="header-section-number">8.1</span> Introduction to Iteration</a>
<ul class="collapse">
<li><a href="#read-more" id="toc-read-more" class="nav-link" data-scroll-target="#read-more">Read more</a></li>
</ul>
</li>
<li>
<a href="#review-of-lists-and-vectors" id="toc-review-of-lists-and-vectors" class="nav-link" data-scroll-target="#review-of-lists-and-vectors"><span class="header-section-number">8.2</span> Review of Lists and Vectors</a>
<ul class="collapse">
<li><a href="#indexing" id="toc-indexing" class="nav-link" data-scroll-target="#indexing"><span class="header-section-number">8.2.1</span> Indexing</a></li>
</ul>
</li>
<li><a href="#vectorized-operations" id="toc-vectorized-operations" class="nav-link" data-scroll-target="#vectorized-operations"><span class="header-section-number">8.3</span> Vectorized Operations</a></li>
<li>
<a href="#functional-programming" id="toc-functional-programming" class="nav-link" data-scroll-target="#functional-programming"><span class="header-section-number">8.4</span> Functional Programming</a>
<ul class="collapse">
<li><a href="#functional-programming-example" id="toc-functional-programming-example" class="nav-link" data-scroll-target="#functional-programming-example">Functional Programming Example</a></li>
</ul>
</li>
<li>
<a href="#introduction-to-map" id="toc-introduction-to-map" class="nav-link" data-scroll-target="#introduction-to-map"><span class="header-section-number">8.5</span> Introduction to <code>map()</code></a>
<ul class="collapse">
<li><a href="#data-setup" id="toc-data-setup" class="nav-link" data-scroll-target="#data-setup"><span class="header-section-number">8.5.1</span> Data Setup</a></li>
<li><a href="#exploring-the-data" id="toc-exploring-the-data" class="nav-link" data-scroll-target="#exploring-the-data"><span class="header-section-number">8.5.2</span> Exploring the Data</a></li>
<li><a href="#map-inside-mutate" id="toc-map-inside-mutate" class="nav-link" data-scroll-target="#map-inside-mutate"><span class="header-section-number">8.5.3</span> Map inside Mutate</a></li>
<li><a href="#creating-and-using-list-columns" id="toc-creating-and-using-list-columns" class="nav-link" data-scroll-target="#creating-and-using-list-columns"><span class="header-section-number">8.5.4</span> Creating (and Using) List-columns</a></li>
<li><a href="#ways-to-use-map" id="toc-ways-to-use-map" class="nav-link" data-scroll-target="#ways-to-use-map"><span class="header-section-number">8.5.5</span> Ways to use <code>map</code></a></li>
<li><a href="#example" id="toc-example" class="nav-link" data-scroll-target="#example">Example</a></li>
<li><a href="#tutorial" id="toc-tutorial" class="nav-link" data-scroll-target="#tutorial">Tutorial</a></li>
<li><a href="#learn-more-about-purrr" id="toc-learn-more-about-purrr" class="nav-link" data-scroll-target="#learn-more-about-purrr">Learn More About Purrr</a></li>
<li><a href="#checkin8-1" id="toc-checkin8-1" class="nav-link" data-scroll-target="#checkin8-1">Check-in 8.1: Functional Programming with the <code>map()</code> family</a></li>
</ul>
</li>
<li><a href="#pa-8-the-12-days-of-christmas-starter-functions" id="toc-pa-8-the-12-days-of-christmas-starter-functions" class="nav-link" data-scroll-target="#pa-8-the-12-days-of-christmas-starter-functions">PA 8: The 12 Days of Christmas Starter Functions</a></li>
<li><a href="#references" id="toc-references" class="nav-link" data-scroll-target="#references">References</a></li>
</ul><div class="toc-actions"><div><i class="bi bi-github"></i></div><div class="action-links"><p><a href="https://github.com/earobinson95/stat331-calpoly-text/edit/main/08-functional-programming.qmd" class="toc-action">Edit this page</a></p></div></div></nav>
</div>
<!-- main -->
<main class="content page-columns page-full" id="quarto-document-content"><header id="title-block-header" class="quarto-title-block default"><div class="quarto-title">
<h1 class="title">
<span class="chapter-number">8</span> <span class="chapter-title">Functional Programming</span>
</h1>
</div>
<div class="quarto-title-meta">
</div>
</header><p><svg aria-hidden="true" role="img" viewbox="0 0 576 512" style="height:1em;width:1.12em;vertical-align:-0.125em;margin-left:auto;margin-right:auto;font-size:inherit;fill:currentColor;overflow:visible;position:relative;"><path d="M249.6 471.5c10.8 3.8 22.4-4.1 22.4-15.5V78.6c0-4.2-1.6-8.4-5-11C247.4 52 202.4 32 144 32C93.5 32 46.3 45.3 18.1 56.1C6.8 60.5 0 71.7 0 83.8V454.1c0 11.9 12.8 20.2 24.1 16.5C55.6 460.1 105.5 448 144 448c33.9 0 79 14 105.6 23.5zm76.8 0C353 462 398.1 448 432 448c38.5 0 88.4 12.1 119.9 22.6c11.3 3.8 24.1-4.6 24.1-16.5V83.8c0-12.1-6.8-23.3-18.1-27.6C529.7 45.3 482.5 32 432 32c-58.4 0-103.4 20-123 35.6c-3.3 2.6-5 6.8-5 11V456c0 11.4 11.7 19.3 22.4 15.5z"></path></svg> Reading: 18 minute(s) at 200 WPM</p>
<p><svg aria-hidden="true" role="img" viewbox="0 0 576 512" style="height:1em;width:1.12em;vertical-align:-0.125em;margin-left:auto;margin-right:auto;font-size:inherit;fill:currentColor;overflow:visible;position:relative;"><path d="M0 128C0 92.7 28.7 64 64 64H320c35.3 0 64 28.7 64 64V384c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V128zM559.1 99.8c10.4 5.6 16.9 16.4 16.9 28.2V384c0 11.8-6.5 22.6-16.9 28.2s-23 5-32.9-1.6l-96-64L416 337.1V320 192 174.9l14.2-9.5 96-64c9.8-6.5 22.4-7.2 32.9-1.6z"></path></svg> Videos: 29 minute(s)</p>
<section id="ch8-objectives" class="level2 unnumbered"><h2 class="unnumbered anchored" data-anchor-id="ch8-objectives">Objectives</h2>
<ul>
<li>Use functional programming techniques to create code which is well organized and easier to understand and maintain</li>
</ul></section><section id="ch8-checkins" class="level2 unnumbered check-in"><h2 class="unnumbered anchored" data-anchor-id="ch8-checkins">Check-ins</h2>
<p>There is one check-in for this week:</p>
<ul>
<li><a href="#checkin8-1">Check-in 8.1: Functional Programming with the <code>map()</code> family</a></li>
</ul></section><section id="introduction-to-iteration" class="level2 page-columns page-full" data-number="8.1"><h2 data-number="8.1" class="anchored" data-anchor-id="introduction-to-iteration">
<span class="header-section-number">8.1</span> Introduction to Iteration</h2>
<p>We just learned the rule of “don’t repeat yourself more than two times” and to instead automate our procedures with functions in order to remove duplication of code. We have used tools such as <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> to help eliminate this copy-paste procedure even further. This is a form of iteration in programming as <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code> “iterates” over variables, applying a function to manipulate each variable and then doing the same for the next variable.</p>
<div class="no-row-height column-margin column-container"><div class="">
<div class="youtube-video-container">
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/7YF6mwTMNZw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen="">
</iframe>
</div>
</div></div><p><code>while()</code> and <code>for()</code> loops are a common form of iteration that can be extremely useful when logically thinking through a problem, however are extremely computationally intensive. Therefore, loops will not be the focus of this chapter. If you are interested, you can go read about <a href="00-prereading.html#prereading-loops">loops</a> in the pre-reading material of this text.</p>
<section id="read-more" class="level3 unnumbered learn-more"><h3 class="unnumbered anchored" data-anchor-id="read-more">Read more</h3>
<p>You can read all about <a href="https://r4ds.had.co.nz/iteration.html#iteration">iteration</a> in the previous version of R4DS.</p>
</section></section><section id="review-of-lists-and-vectors" class="level2" data-number="8.2"><h2 data-number="8.2" class="anchored" data-anchor-id="review-of-lists-and-vectors">
<span class="header-section-number">8.2</span> Review of Lists and Vectors</h2>
<p>In the pre-reading, we introduce the different <a href="00-prereading.html#data-structures">data structures</a> we have worked with in R. We are going to do a review of some of the important data structures for this chapter.</p>
<p>A <strong>vector</strong> is a 1-dimensional data structure that contains items of the same simple (‘atomic’) type (character, logical, integer, factor).</p>
<div class="cell">
<div class="sourceCode" id="cb1" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="op">(</span><span class="va">logical_vec</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="cn">T</span>, <span class="cn">F</span>, <span class="cn">T</span>, <span class="cn">T</span><span class="op">)</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] TRUE FALSE TRUE TRUE</code></pre>
</div>
<div class="sourceCode" id="cb3" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="op">(</span><span class="va">numeric_vec</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="fl">3</span>, <span class="fl">1</span>, <span class="fl">4</span>, <span class="fl">5</span><span class="op">)</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] 3 1 4 5</code></pre>
</div>
<div class="sourceCode" id="cb5" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="op">(</span><span class="va">char_vec</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"A"</span>, <span class="st">"AB"</span>, <span class="st">"ABC"</span>, <span class="st">"ABCD"</span><span class="op">)</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] "A" "AB" "ABC" "ABCD"</code></pre>
</div>
</div>
<p>You <strong>index</strong> a vector using brackets: to get the <span class="math inline">\(i\)</span>th element of the vector <code>x</code>, you would use <code>x[i]</code> in R or <code>x[i-1]</code> in python (Remember, python is 0-indexed, so the first element of the vector is at location 0).</p>
<div class="cell">
<div class="sourceCode" id="cb7" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">logical_vec</span><span class="op">[</span><span class="fl">3</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] TRUE</code></pre>
</div>
<div class="sourceCode" id="cb9" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">numeric_vec</span><span class="op">[</span><span class="fl">3</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] 4</code></pre>
</div>
<div class="sourceCode" id="cb11" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">char_vec</span><span class="op">[</span><span class="fl">3</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] "ABC"</code></pre>
</div>
</div>
<p>You can also index a vector using a logical vector:</p>
<div class="cell">
<div class="sourceCode" id="cb13" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">numeric_vec</span><span class="op">[</span><span class="va">logical_vec</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] 3 4 5</code></pre>
</div>
<div class="sourceCode" id="cb15" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">char_vec</span><span class="op">[</span><span class="va">logical_vec</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] "A" "ABC" "ABCD"</code></pre>
</div>
<div class="sourceCode" id="cb17" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">logical_vec</span><span class="op">[</span><span class="va">logical_vec</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] TRUE TRUE TRUE</code></pre>
</div>
</div>
<p>A <strong>list</strong> is a 1-dimensional data structure that has no restrictions on what type of content is stored within it. A list is a “vector”, but it is not an atomic vector - that is, it does not necessarily contain things that are all the same type.</p>
<div class="cell">
<div class="sourceCode" id="cb19" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="op">(</span></span>
<span> <span class="va">mylist</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/base/list.html">list</a></span><span class="op">(</span></span>
<span> <span class="va">logical_vec</span>, </span>
<span> <span class="va">numeric_vec</span>, </span>
<span> third_thing <span class="op">=</span> <span class="va">char_vec</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">2</span><span class="op">]</span></span>
<span> <span class="op">)</span></span>
<span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[[1]]
[1] TRUE FALSE TRUE TRUE
[[2]]
[1] 3 1 4 5
$third_thing
[1] "A" "AB"</code></pre>
</div>
</div>
<p>List components may have names (or not), be homogeneous (or not), have the same length (or not).</p>
<section id="indexing" class="level3" data-number="8.2.1"><h3 data-number="8.2.1" class="anchored" data-anchor-id="indexing">
<span class="header-section-number">8.2.1</span> Indexing</h3>
<p>Indexing necessarily differs between R and python, and since the list types are also somewhat different (e.g. lists cannot be named in python), we will treat list indexing in the two languages separately.</p>
<div id="fig-pepper" class="quarto-layout-panel">
<figure class="figure"><div class="quarto-layout-row quarto-layout-valign-top">
<div class="quarto-layout-cell" style="flex-basis: 25.0%;justify-content: center;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure"><p><img src="images/08-functional-programming/02_pepper.jpg" class="img-fluid figure-img" alt="A pepper shaker containing several individual paper packets of pepper"></p>
<figcaption class="figure-caption">An unusual pepper shaker which we’ll call <code>pepper</code></figcaption></figure>
</div>
</div>
<div class="quarto-layout-cell" style="flex-basis: 25.0%;justify-content: center;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure"><p><img src="images/08-functional-programming/02_pepper-1.jpg" class="img-fluid figure-img" alt="A pepper shaker containing a single individual paper packet of pepper."></p>
<figcaption class="figure-caption">When a list is indexed with single brackets, <code>pepper[1]</code>, the return value is always a list containing the selected element(s).</figcaption></figure>
</div>
</div>
<div class="quarto-layout-cell" style="flex-basis: 25.0%;justify-content: center;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure"><p><img src="images/08-functional-programming/02_pepper-2.jpg" class="img-fluid figure-img" alt="A single individual paper packet of pepper, no longer contained within a pepper shaker."></p>
<figcaption class="figure-caption">When a list is indexed with double brackets, <code>pepper[[1]]</code>, the return value is the selected element.</figcaption></figure>
</div>
</div>
<div class="quarto-layout-cell" style="flex-basis: 25.0%;justify-content: center;">
<div class="quarto-figure quarto-figure-center">
<figure class="figure"><p><img src="images/08-functional-programming/02_pepper-3.jpg" class="img-fluid figure-img" alt="A pile of pepper, free from any containment structures."></p>
<figcaption class="figure-caption">To actually access the pepper, we have to use double indexing and index both the list object and the sub-object, as in <code>pepper[[1]][[1]]</code>.</figcaption></figure>
</div>
</div>
</div>
<p></p><figcaption class="figure-caption">Figure 8.1: The types of indexing are made most memorable with a fantastic visual example from <span class="citation" data-cites="r4ds">Grolemund and Wickham (<a href="#ref-r4ds" role="doc-biblioref">2017</a>)</span>, which I have repeated here.</figcaption><p></p>
</figure>
</div>
<p>There are 3 ways to index a list:</p>
<ul>
<li>With single square brackets, just like we index atomic vectors. In this case, the return value is always a list.</li>
</ul>
<div class="cell">
<div class="sourceCode" id="cb21" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">mylist</span><span class="op">[</span><span class="fl">1</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[[1]]
[1] TRUE FALSE TRUE TRUE</code></pre>
</div>
<div class="sourceCode" id="cb23" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">mylist</span><span class="op">[</span><span class="fl">2</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[[1]]
[1] 3 1 4 5</code></pre>
</div>
<div class="sourceCode" id="cb25" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">mylist</span><span class="op">[</span><span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="cn">T</span>, <span class="cn">F</span>, <span class="cn">T</span><span class="op">)</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[[1]]
[1] TRUE FALSE TRUE TRUE
$third_thing
[1] "A" "AB"</code></pre>
</div>
</div>
<ul>
<li>With double square brackets. In this case, the return value is the thing inside the specified position in the list, but you also can only get one entry in the main list at a time. You can also get things by name.</li>
</ul>
<div class="cell">
<div class="sourceCode" id="cb27" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">mylist</span><span class="op">[[</span><span class="fl">1</span><span class="op">]</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] TRUE FALSE TRUE TRUE</code></pre>
</div>
<div class="sourceCode" id="cb29" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">mylist</span><span class="op">[[</span><span class="st">"third_thing"</span><span class="op">]</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] "A" "AB"</code></pre>
</div>
</div>
<ul>
<li>Using <code>x$name</code>. This is equivalent to using <code>x[["name"]]</code>. Note that this does not work on unnamed entries in the list.</li>
</ul>
<div class="cell">
<div class="sourceCode" id="cb31" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">mylist</span><span class="op">$</span><span class="va">third_thing</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] "A" "AB"</code></pre>
</div>
</div>
<p>To access the contents of a list object, we have to use double-indexing:</p>
<div class="cell">
<div class="sourceCode" id="cb33" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">mylist</span><span class="op">[[</span><span class="st">"third_thing"</span><span class="op">]</span><span class="op">]</span><span class="op">[[</span><span class="fl">1</span><span class="op">]</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] "A"</code></pre>
</div>
</div>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>You can get a more thorough review of vectors and lists <a href="https://jennybc.github.io/purrr-tutorial/bk00_vectors-and-lists.html">from Jenny Bryan’s purrr tutorial introduction</a> <span class="citation" data-cites="bryanLessonsExamples20191021">(<a href="#ref-bryanLessonsExamples20191021" role="doc-biblioref">Bryan n.d.</a>)</span>.</p>
</div>
</div>
</section></section><section id="vectorized-operations" class="level2 page-columns page-full" data-number="8.3"><h2 data-number="8.3" class="anchored" data-anchor-id="vectorized-operations">
<span class="header-section-number">8.3</span> Vectorized Operations</h2>
<p>Operations in R are (usually) <strong>vectorized</strong> - that is, by default, they operate on vectors. This is primarily a feature that applies to atomic vectors (and we don’t even think about it):</p>
<div class="no-row-height column-margin column-container"><div class="">
<div class="youtube-video-container">
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/sxIX9lzPjDQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen="">
</iframe>
</div>
</div></div><div class="cell">
<div class="sourceCode" id="cb35" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="op">(</span><span class="fu"><a href="https://rdrr.io/r/stats/Normal.html">rnorm</a></span><span class="op">(</span><span class="fl">10</span><span class="op">)</span> <span class="op">+</span> <span class="fu"><a href="https://rdrr.io/r/stats/Normal.html">rnorm</a></span><span class="op">(</span><span class="fl">10</span>, mean <span class="op">=</span> <span class="fl">3</span><span class="op">)</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> [1] 3.7285369 0.7166789 3.8175248 2.4609676 4.7094032 1.6242776 3.9324809
[8] 5.8978374 2.7208493 4.8787993</code></pre>
</div>
</div>
<p>With vectorized functions, we don’t have to use a for loop to add these two vectors with 10 entries each together. In languages which don’t have implicit support for vectorized computations, this might instead look like:</p>
<div class="cell">
<div class="sourceCode" id="cb37" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">a</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/stats/Normal.html">rnorm</a></span><span class="op">(</span><span class="fl">10</span><span class="op">)</span></span>
<span><span class="va">b</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/stats/Normal.html">rnorm</a></span><span class="op">(</span><span class="fl">10</span>, mean <span class="op">=</span> <span class="fl">3</span><span class="op">)</span></span>
<span></span>
<span><span class="va">result</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/base/rep.html">rep</a></span><span class="op">(</span><span class="fl">0</span>, <span class="fl">10</span><span class="op">)</span></span>
<span><span class="kw">for</span> <span class="op">(</span><span class="va">i</span> <span class="kw">in</span> <span class="fl">1</span><span class="op">:</span><span class="fl">10</span><span class="op">)</span> <span class="op">{</span></span>
<span> <span class="va">result</span><span class="op">[</span><span class="va">i</span><span class="op">]</span> <span class="op"><-</span> <span class="va">a</span><span class="op">[</span><span class="va">i</span><span class="op">]</span> <span class="op">+</span> <span class="va">b</span><span class="op">[</span><span class="va">i</span><span class="op">]</span></span>
<span><span class="op">}</span></span>
<span></span>
<span><span class="va">result</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> [1] 5.1699090 3.1676718 2.1741276 2.1699792 5.3172499 -0.5303277
[7] 4.9794343 5.3602351 3.6929630 5.0583391</code></pre>
</div>
</div>
<p>That is, we would <strong>apply</strong> or <strong>map</strong> the <code>+</code> function to each entry of a and b. For atomic vectors, it’s easy to do this by default; with a list, however, we need to be a bit more explicit (because everything that’s passed into the function may not be the same type).</p>
<div class="no-row-height column-margin column-container"><div class="">
<p>I find the <code>purrr</code> package easier to work with, so we won’t be working with the base functions in this course. You can find a <a href="https://jennybc.github.io/purrr-tutorial/bk01_base-functions.html">side-by-side comparison in the <code>purrr</code> tutorial</a>.</p>
<p><br></p>
<p>You can also watch Dr. Theobold’s video to learn more:</p>
<div class="youtube-video-container">
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/NadUAnlrh-M" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen="">
</iframe>
</div>
</div></div><p>The R package <code>purrr</code> (and similar base functions <code>apply</code>, <code>lapply</code>, <code>sapply</code>, <code>tapply</code>, and <code>mapply</code>) are based on extending “vectorized” functions to a wider variety of vector-like structures.</p>
</section><section id="functional-programming" class="level2" data-number="8.4"><h2 data-number="8.4" class="anchored" data-anchor-id="functional-programming">
<span class="header-section-number">8.4</span> Functional Programming</h2>
<p>The concept of <strong>functional programming</strong> is a bit hard to define rigorously at the level we’re working at, but generally, functional programming is concerned with <strong>pure functions</strong>: functions that have an input value that determines the output value and create no other side effects.</p>
<p>What this means is that you describe every step of the computation using a function, and chain the functions together. At the end of the computations, you might save the program’s results to an object, but (in general), the goal is to not change things outside of the “pipeline” along the way.</p>
<p>This has some advantages:</p>
<ul>
<li>Easier parallelization
<ul>
<li>“Side effects” generally make it hard to parallelize code because e.g. you have to update stored objects in memory, which is hard to do with multiple threads accessing the same memory.</li>
</ul>
</li>
<li>Functional programming tends to be easier to read
<ul>
<li>You can see output and input and don’t have to work as hard to keep track of what is stored where .</li>
</ul>
</li>
<li>Easier Debugging
<ul>
<li>You can examine the input and output at each stage to isolate which function is introducing the problem.</li>
</ul>
</li>
</ul>
<p>The introduction of the pipe in R has made chaining functions together in a functional programming-style pipeline much easier. <code>purrr</code> is just another step in this process: by making it easy to apply functions to lists of things (or to use multiple lists of things in a single function), <code>purrr</code> makes it easier to write clean, understandable, debuggable code.</p>
<p><br></p>
<section id="functional-programming-example" class="level3 unnumbered ex"><h3 class="unnumbered anchored" data-anchor-id="functional-programming-example">Functional Programming Example</h3>
<p>This example is modified from the motivation section of the <a href="http://adv-r.had.co.nz/Functional-programming.html">Functional Programming chapter</a> in Advanced R <span class="citation" data-cites="wickhamFunctionalProgramming2019">(<a href="#ref-wickhamFunctionalProgramming2019" role="doc-biblioref">Wickham 2019</a>)</span>.</p>
<div class="tabset-margin-container"></div><div class="panel-tabset">
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" role="presentation"><a class="nav-link active" id="tabset-1-1-tab" data-bs-toggle="tab" data-bs-target="#tabset-1-1" role="tab" aria-controls="tabset-1-1" aria-selected="true">Problem</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="tabset-1-2-tab" data-bs-toggle="tab" data-bs-target="#tabset-1-2" role="tab" aria-controls="tabset-1-2" aria-selected="false">Naive Approach</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="tabset-1-3-tab" data-bs-toggle="tab" data-bs-target="#tabset-1-3" role="tab" aria-controls="tabset-1-3" aria-selected="false">Writing a function</a></li>
<li class="nav-item" role="presentation"><a class="nav-link" id="tabset-1-4-tab" data-bs-toggle="tab" data-bs-target="#tabset-1-4" role="tab" aria-controls="tabset-1-4" aria-selected="false">Mapping a function</a></li>
</ul>
<div class="tab-content">
<div id="tabset-1-1" class="tab-pane active" role="tabpanel" aria-labelledby="tabset-1-1-tab">
<p>Suppose we want to replace every -99 in the following sample dataset with an NA. (-99 is sometimes used to indicate missingness in datasets).</p>
<div class="cell">
<div class="sourceCode" id="cb39" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="co"># Generate a sample dataset</span></span>
<span><span class="fu"><a href="https://rdrr.io/r/base/Random.html">set.seed</a></span><span class="op">(</span><span class="fl">1014</span><span class="op">)</span></span>
<span><span class="va">df</span> <span class="op"><-</span> <span class="fu"><a href="https://rdrr.io/r/base/data.frame.html">data.frame</a></span><span class="op">(</span><span class="fu"><a href="https://rdrr.io/r/base/lapply.html">replicate</a></span><span class="op">(</span><span class="fl">6</span>, <span class="fu"><a href="https://rdrr.io/r/base/sample.html">sample</a></span><span class="op">(</span><span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="fl">1</span><span class="op">:</span><span class="fl">10</span>, <span class="op">-</span><span class="fl">99</span><span class="op">)</span>, <span class="fl">6</span>, rep <span class="op">=</span> <span class="cn">TRUE</span><span class="op">)</span><span class="op">)</span><span class="op">)</span></span>
<span><span class="fu"><a href="https://rdrr.io/r/base/names.html">names</a></span><span class="op">(</span><span class="va">df</span><span class="op">)</span> <span class="op"><-</span> <span class="va">letters</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">6</span><span class="op">]</span></span>
<span><span class="va">df</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> a b c d e f
1 7 5 -99 2 5 2
2 5 5 5 3 6 1
3 6 8 5 9 9 4
4 4 2 2 6 6 8
5 6 7 6 -99 10 6
6 9 -99 4 7 5 1</code></pre>
</div>
</div>
</div>
<div id="tabset-1-2" class="tab-pane" role="tabpanel" aria-labelledby="tabset-1-2-tab">
<p>The “beginner” approach is to just replace each individual -99 with an NA:</p>
<div class="cell">
<div class="sourceCode" id="cb41" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">df1</span> <span class="op"><-</span> <span class="va">df</span></span>
<span><span class="va">df1</span><span class="op">[</span><span class="fl">6</span>,<span class="fl">2</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df1</span><span class="op">[</span><span class="fl">1</span>,<span class="fl">3</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df1</span><span class="op">[</span><span class="fl">5</span>,<span class="fl">4</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span></span>
<span><span class="va">df1</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> a b c d e f
1 7 5 NA 2 5 2
2 5 5 5 3 6 1
3 6 8 5 9 9 4
4 4 2 2 6 6 8
5 6 7 6 NA 10 6
6 9 NA 4 7 5 1</code></pre>
</div>
</div>
<p>This is tedious, and painful, and won’t work if we have a slightly different dataset where the -99s are in different places. So instead, we might consider being a bit more general:</p>
<div class="cell">
<div class="sourceCode" id="cb43" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">df2</span> <span class="op"><-</span> <span class="va">df</span></span>
<span><span class="va">df2</span><span class="op">$</span><span class="va">a</span><span class="op">[</span><span class="va">df2</span><span class="op">$</span><span class="va">a</span> <span class="op">==</span> <span class="op">-</span><span class="fl">99</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df2</span><span class="op">$</span><span class="va">b</span><span class="op">[</span><span class="va">df2</span><span class="op">$</span><span class="va">b</span> <span class="op">==</span> <span class="op">-</span><span class="fl">99</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df2</span><span class="op">$</span><span class="va">c</span><span class="op">[</span><span class="va">df2</span><span class="op">$</span><span class="va">c</span> <span class="op">==</span> <span class="op">-</span><span class="fl">99</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df2</span><span class="op">$</span><span class="va">d</span><span class="op">[</span><span class="va">df2</span><span class="op">$</span><span class="va">d</span> <span class="op">==</span> <span class="op">-</span><span class="fl">99</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df2</span><span class="op">$</span><span class="va">e</span><span class="op">[</span><span class="va">df2</span><span class="op">$</span><span class="va">e</span> <span class="op">==</span> <span class="op">-</span><span class="fl">99</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df2</span><span class="op">$</span><span class="va">f</span><span class="op">[</span><span class="va">df2</span><span class="op">$</span><span class="va">f</span> <span class="op">==</span> <span class="op">-</span><span class="fl">99</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span><span class="va">df2</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> a b c d e f
1 7 5 NA 2 5 2
2 5 5 5 3 6 1
3 6 8 5 9 9 4
4 4 2 2 6 6 8
5 6 7 6 NA 10 6
6 9 NA 4 7 5 1</code></pre>
</div>
</div>
<p>This requires a few more lines of code, but is able to handle any data frame with 6 columns <code>a</code> - <code>f</code>. It also requires a lot of copy-paste and can leave you vulnerable to making mistakes.</p>
</div>
<div id="tabset-1-3" class="tab-pane" role="tabpanel" aria-labelledby="tabset-1-3-tab">
<p>The standard rule is that if you copy-paste the same code 3x, then you should write a function, so let’s try that instead:</p>
<div class="cell">
<div class="sourceCode" id="cb45" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">fix_missing</span> <span class="op"><-</span> <span class="kw">function</span><span class="op">(</span><span class="va">x</span>, <span class="va">missing</span> <span class="op">=</span> <span class="op">-</span><span class="fl">99</span><span class="op">)</span><span class="op">{</span></span>
<span> <span class="va">x</span><span class="op">[</span><span class="va">x</span> <span class="op">==</span> <span class="va">missing</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span> <span class="va">x</span></span>
<span><span class="op">}</span></span>
<span></span>
<span><span class="va">df3</span> <span class="op"><-</span> <span class="va">df</span></span>
<span><span class="va">df3</span><span class="op">$</span><span class="va">a</span> <span class="op"><-</span> <span class="fu">fix_missing</span><span class="op">(</span><span class="va">df</span><span class="op">$</span><span class="va">a</span><span class="op">)</span></span>
<span><span class="va">df3</span><span class="op">$</span><span class="va">b</span> <span class="op"><-</span> <span class="fu">fix_missing</span><span class="op">(</span><span class="va">df</span><span class="op">$</span><span class="va">b</span><span class="op">)</span></span>
<span><span class="va">df3</span><span class="op">$</span><span class="va">c</span> <span class="op"><-</span> <span class="fu">fix_missing</span><span class="op">(</span><span class="va">df</span><span class="op">$</span><span class="va">c</span><span class="op">)</span></span>
<span><span class="va">df3</span><span class="op">$</span><span class="va">d</span> <span class="op"><-</span> <span class="fu">fix_missing</span><span class="op">(</span><span class="va">df</span><span class="op">$</span><span class="va">d</span><span class="op">)</span></span>
<span><span class="va">df3</span><span class="op">$</span><span class="va">e</span> <span class="op"><-</span> <span class="fu">fix_missing</span><span class="op">(</span><span class="va">df</span><span class="op">$</span><span class="va">e</span><span class="op">)</span></span>
<span><span class="va">df3</span><span class="op">$</span><span class="va">f</span> <span class="op"><-</span> <span class="fu">fix_missing</span><span class="op">(</span><span class="va">df</span><span class="op">$</span><span class="va">f</span><span class="op">)</span></span>
<span><span class="va">df3</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> a b c d e f
1 7 5 NA 2 5 2
2 5 5 5 3 6 1
3 6 8 5 9 9 4
4 4 2 2 6 6 8
5 6 7 6 NA 10 6
6 9 NA 4 7 5 1</code></pre>
</div>
</div>
<p>This still requires a lot of copy-paste, and doesn’t actually make the code more readable. We can more easily change the missing value, though, which is a bonus.</p>
</div>
<div id="tabset-1-4" class="tab-pane" role="tabpanel" aria-labelledby="tabset-1-4-tab">
<p>We have a function that we want to <strong>apply</strong> or <strong>map</strong> to every column in our data frame. We could use a <code>for()</code> loop (doing this for demonstrative purposes only, I expect you to use more efficient tools in class):</p>
<div class="cell">
<div class="sourceCode" id="cb47" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">fix_missing</span> <span class="op"><-</span> <span class="kw">function</span><span class="op">(</span><span class="va">x</span>, <span class="va">missing</span> <span class="op">=</span> <span class="op">-</span><span class="fl">99</span><span class="op">)</span><span class="op">{</span></span>
<span> <span class="va">x</span><span class="op">[</span><span class="va">x</span> <span class="op">==</span> <span class="va">missing</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span> <span class="va">x</span></span>
<span><span class="op">}</span></span>
<span></span>
<span><span class="va">df4</span> <span class="op"><-</span> <span class="va">df</span></span>
<span><span class="kw">for</span> <span class="op">(</span><span class="va">i</span> <span class="kw">in</span> <span class="fl">1</span><span class="op">:</span><span class="fu"><a href="https://rdrr.io/r/base/nrow.html">ncol</a></span><span class="op">(</span><span class="va">df</span><span class="op">)</span><span class="op">)</span> <span class="op">{</span></span>
<span> <span class="va">df4</span><span class="op">[</span>,<span class="va">i</span><span class="op">]</span> <span class="op"><-</span> <span class="fu">fix_missing</span><span class="op">(</span><span class="va">df4</span><span class="op">[</span>,<span class="va">i</span><span class="op">]</span><span class="op">)</span></span>
<span><span class="op">}</span></span>
<span><span class="va">df4</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> a b c d e f
1 7 5 NA 2 5 2
2 5 5 5 3 6 1
3 6 8 5 9 9 4
4 4 2 2 6 6 8
5 6 7 6 NA 10 6
6 9 NA 4 7 5 1</code></pre>
</div>
</div>
<p>This is more understandable and flexible than the previous function approach as well as the naive approach - we don’t need to know the names of the columns in our data frame, or even how many there are. It is still quite a few lines of code, though.</p>
<p>Iterating through a list (or columns of a data frame) is a very common task, so R has a shorthand function for it. You could us <code>lapply</code> from base R, but we will be learning the <code>map</code> family of functions from the <code>purrr</code> package.</p>
<div class="cell">
<div class="sourceCode" id="cb49" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">fix_missing</span> <span class="op"><-</span> <span class="kw">function</span><span class="op">(</span><span class="va">x</span>, <span class="va">missing</span> <span class="op">=</span> <span class="op">-</span><span class="fl">99</span><span class="op">)</span><span class="op">{</span></span>
<span> <span class="va">x</span><span class="op">[</span><span class="va">x</span> <span class="op">==</span> <span class="va">missing</span><span class="op">]</span> <span class="op"><-</span> <span class="cn">NA</span></span>
<span> <span class="va">x</span></span>
<span><span class="op">}</span></span>
<span></span>
<span><span class="va">df5</span> <span class="op"><-</span> <span class="va">df</span></span>
<span><span class="va">df5</span> <span class="op"><-</span> <span class="fu">map_dfc</span><span class="op">(</span><span class="va">df5</span>, <span class="va">fix_missing</span><span class="op">)</span></span>
<span><span class="va">df5</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code># A tibble: 6 × 6
a b c d e f
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 7 5 NA 2 5 2
2 5 5 5 3 6 1
3 6 8 5 9 9 4
4 4 2 2 6 6 8
5 6 7 6 NA 10 6
6 9 NA 4 7 5 1</code></pre>
</div>
</div>
<p>By default, <code>map</code> returns a list (see below), but we can use <code>map_dfc</code> to return a data frame created by binding the columns together.</p>
<details><summary><code>map()</code> - returns a list
</summary><div class="cell">
<div class="sourceCode" id="cb51" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">df6</span> <span class="op"><-</span> <span class="va">df</span></span>
<span><span class="fu">map</span><span class="op">(</span><span class="va">df6</span>, <span class="va">fix_missing</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>$a
[1] 7 5 6 4 6 9
$b
[1] 5 5 8 2 7 NA
$c
[1] NA 5 5 2 6 4
$d
[1] 2 3 9 6 NA 7
$e
[1] 5 6 9 6 10 5
$f
[1] 2 1 4 8 6 1</code></pre>
</div>
</div>
</details><p>We’ve replaced 6 lines of code that only worked for 6 columns named <code>a</code> - <code>f</code> with a single line of code that works for any data frame with any number of rows and columns, so long as -99 indicates missing data. In addition to being shorter, this code is also somewhat easier to read and much less vulnerable to typos.</p>
</div>
</div>
</div>
</section></section><section id="introduction-to-map" class="level2 page-columns page-full" data-number="8.5"><h2 data-number="8.5" class="anchored" data-anchor-id="introduction-to-map">
<span class="header-section-number">8.5</span> Introduction to <code>map()</code>
</h2>
<div class="note">
<p><code>purrr</code> is a part of the tidyverse, so you should already have the package installed. When you load the tidyverse with <code><a href="https://rdrr.io/r/base/library.html">library()</a></code>, this also loads <code>purrr</code>.</p>
<div class="cell">
<div class="sourceCode" id="cb53" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu"><a href="https://rdrr.io/r/utils/install.packages.html">install.packages</a></span><span class="op">(</span><span class="st">"purrr"</span><span class="op">)</span></span>
<span><span class="kw"><a href="https://rdrr.io/r/base/library.html">library</a></span><span class="op">(</span><span class="va"><a href="https://purrr.tidyverse.org/">purrr</a></span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p><a href="https://posit.co/wp-content/uploads/2022/10/purrr.pdf">Download the <code>purrr</code> cheatsheet</a>.</p>
</div>
<div class="no-row-height column-margin column-container"><div class="">
<div class="youtube-video-container">
<iframe width="100%" height="auto" src="https://www.youtube.com/embed/FPD3a6IHO6w" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen="">
</iframe>
</div>
</div></div><section id="data-setup" class="level3 page-columns page-full" data-number="8.5.1"><h3 data-number="8.5.1" class="anchored" data-anchor-id="data-setup">
<span class="header-section-number">8.5.1</span> Data Setup</h3>
<p>We’ll use one of the datasets in the <code>repurrsive</code> package, <code>got_chars</code>, to start playing with the <code>map_</code> series of functions. First, let’s export the data from <code>repurrrsive</code> to a JSON file that we can read into R.</p>
<div class="no-row-height column-margin column-container"><div class="">
<p>The source data for this example comes from <a href="https://anapioficeandfire.com/">An API of Ice and Fire</a> and is fairly typical for API (automatic programming interface) data in both cleanliness and complexity.</p>
</div></div><div class="cell">
<div class="sourceCode" id="cb54" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="kw"><a href="https://rdrr.io/r/base/library.html">library</a></span><span class="op">(</span><span class="va"><a href="https://jennybc.github.io/repurrrsive/">repurrrsive</a></span><span class="op">)</span> <span class="co"># example data</span></span>
<span><span class="fu"><a href="https://rdrr.io/r/utils/data.html">data</a></span><span class="op">(</span><span class="va">got_chars</span><span class="op">)</span></span>
<span></span>
<span><span class="kw"><a href="https://rdrr.io/r/base/library.html">library</a></span><span class="op">(</span><span class="va"><a href="https://github.com/alexcb/rjson">rjson</a></span><span class="op">)</span></span>
<span><span class="fu"><a href="https://rdrr.io/r/base/write.html">write</a></span><span class="op">(</span><span class="fu">toJSON</span><span class="op">(</span><span class="va">got_chars</span><span class="op">)</span>, <span class="st">"data/got_chars.json"</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div class="cell">
<div class="sourceCode" id="cb55" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="kw"><a href="https://rdrr.io/r/base/library.html">library</a></span><span class="op">(</span><span class="va"><a href="https://purrr.tidyverse.org/">purrr</a></span><span class="op">)</span> <span class="co"># functions for working with lists</span></span>
<span><span class="va">got_chars</span> <span class="op"><-</span> <span class="fu">fromJSON</span><span class="op">(</span>file <span class="op">=</span> <span class="st">"data/got_chars.json"</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div class="cell">
<div class="sourceCode" id="cb56" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu"><a href="https://rdrr.io/r/base/length.html">length</a></span><span class="op">(</span><span class="va">got_chars</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] 30</code></pre>
</div>
<div class="sourceCode" id="cb58" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">got_chars</span><span class="op">[[</span><span class="fl">1</span><span class="op">]</span><span class="op">]</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">6</span><span class="op">]</span> <span class="co"># Only show the first 6 fields</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>$url
[1] "https://www.anapioficeandfire.com/api/characters/1022"
$id
[1] 1022
$name
[1] "Theon Greyjoy"
$gender
[1] "Male"
$culture
[1] "Ironborn"
$born
[1] "In 278 AC or 279 AC, at Pyke"</code></pre>
</div>
<div class="sourceCode" id="cb60" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu"><a href="https://rdrr.io/r/base/names.html">names</a></span><span class="op">(</span><span class="va">got_chars</span><span class="op">[[</span><span class="fl">1</span><span class="op">]</span><span class="op">]</span><span class="op">)</span> <span class="co"># How many total fields? names?</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> [1] "url" "id" "name" "gender" "culture"
[6] "born" "died" "alive" "titles" "aliases"
[11] "father" "mother" "spouse" "allegiances" "books"
[16] "povBooks" "tvSeries" "playedBy" </code></pre>
</div>
</div>
<p>It appears that each entry in this 30-item list is a character from Game of Thrones, and there are several sub-fields for each character.</p>
</section><section id="exploring-the-data" class="level3" data-number="8.5.2"><h3 data-number="8.5.2" class="anchored" data-anchor-id="exploring-the-data">
<span class="header-section-number">8.5.2</span> Exploring the Data</h3>
<p>What characters do we have? How is the data structured?</p>
<p>List data can be incredibly hard to work with because the structure is so flexible. It’s important to have a way to visualize the structure of a complex list object: the <code><a href="https://rdrr.io/r/utils/View.html">View()</a></code> command in RStudio is one good way to explore and poke around a list.</p>
<div class="panel-ex">
<p>We can use <code>purrr::map(x, "name")</code> to get a list of all characters’ names. Since they are all the same type, we could also use an extension of <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code>, <code><a href="https://purrr.tidyverse.org/reference/map.html">map_chr()</a></code>, which will coerce the returned list into a character vector (which may be simpler to operate on).</p>
<div class="note">
<p>There are several packages with <code><a href="https://purrr.tidyverse.org/reference/map.html">map()</a></code> functions including functions that are meant to actually plot maps; it generally saves time and effort to just type the function name with the package you want in <code>package::function</code> notation. You don’t <em>have</em> to do so, but if you have a lot of other (non tidyverse, in particular) packages loaded, it will save you a lot of grief.</p>
</div>
<div class="cell">
<div class="sourceCode" id="cb62" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map.html">map</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="st">"name"</span><span class="op">)</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">5</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[[1]]
[1] "Theon Greyjoy"
[[2]]
[1] "Tyrion Lannister"
[[3]]
[1] "Victarion Greyjoy"
[[4]]
[1] "Will"
[[5]]
[1] "Areo Hotah"</code></pre>
</div>
<div class="sourceCode" id="cb64" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map.html">map_chr</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="st">"name"</span><span class="op">)</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">5</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[1] "Theon Greyjoy" "Tyrion Lannister" "Victarion Greyjoy"
[4] "Will" "Areo Hotah" </code></pre>
</div>
</div>
<p>Similar shortcuts work to get the nth item in each sub list:</p>
<div class="cell">
<div class="sourceCode" id="cb66" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map.html">map_chr</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="fl">4</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code> [1] "Male" "Male" "Male" "Male" "Male" "Male" "Male" "Female"
[9] "Female" "Male" "Female" "Male" "Female" "Male" "Male" "Male"
[17] "Female" "Female" "Female" "Male" "Male" "Male" "Male" "Male"
[25] "Male" "Female" "Male" "Male" "Male" "Female"</code></pre>
</div>
</div>
<p>Specifying the output type using e.g. <code><a href="https://purrr.tidyverse.org/reference/map.html">map_chr()</a></code> works if each item in the list is an atomic vector of length 1. If the list is more complicated, though, these shortcuts will issue an error:</p>
<div class="cell">
<div class="sourceCode" id="cb68" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map.html">map</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="st">"books"</span><span class="op">)</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">5</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[[1]]
[1] "A Game of Thrones" "A Storm of Swords" "A Feast for Crows"
[[2]]
[1] "A Feast for Crows" "The World of Ice and Fire"
[[3]]
[1] "A Game of Thrones" "A Clash of Kings" "A Storm of Swords"
[[4]]
[1] "A Clash of Kings"
[[5]]
[1] "A Game of Thrones" "A Clash of Kings" "A Storm of Swords"</code></pre>
</div>
<div class="sourceCode" id="cb70" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map.html">map_chr</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="st">"books"</span><span class="op">)</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">5</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-error">
<pre data-code-line-numbers=""><code>Error in `purrr::map_chr()`:
ℹ In index: 1.
Caused by error:
! Result must be length 1, not 3.</code></pre>
</div>
</div>
<p>What if we want to extract several things? This trick works off of the idea that <code>[</code> is a function: that is, the single brackets we used before are actually a special type of function. In R functions, there is often the argument <code>...</code>, which is a convention that allows us to pass arguments to other functions that are called within the main function we are using (you’ll see … used in plotting and regression functions frequently as well).</p>
<p>Here, we use <code>...</code> to pass in our list of 3 things we want to pull from each item in the list.</p>
<div class="cell">
<div class="sourceCode" id="cb72" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map.html">map</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="va">`[`</span>, <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"name"</span>, <span class="st">"gender"</span>, <span class="st">"born"</span><span class="op">)</span><span class="op">)</span><span class="op">[</span><span class="fl">1</span><span class="op">:</span><span class="fl">5</span><span class="op">]</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code>[[1]]
[[1]]$name
[1] "Theon Greyjoy"
[[1]]$gender
[1] "Male"
[[1]]$born
[1] "In 278 AC or 279 AC, at Pyke"
[[2]]
[[2]]$name
[1] "Tyrion Lannister"
[[2]]$gender
[1] "Male"
[[2]]$born
[1] "In 273 AC, at Casterly Rock"
[[3]]
[[3]]$name
[1] "Victarion Greyjoy"
[[3]]$gender
[1] "Male"
[[3]]$born
[1] "In 268 AC or before, at Pyke"
[[4]]
[[4]]$name
[1] "Will"
[[4]]$gender
[1] "Male"
[[4]]$born
[1] ""
[[5]]
[[5]]$name
[1] "Areo Hotah"
[[5]]$gender
[1] "Male"
[[5]]$born
[1] "In 257 AC or before, at Norvos"</code></pre>
</div>
</div>
<p>What if we want this to be a data frame instead? We can use <code><a href="https://purrr.tidyverse.org/reference/map_dfr.html">map_dfr()</a></code> to get a data frame that is formed by row-binding each element in the list.</p>
<div class="cell">
<div class="sourceCode" id="cb74" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map_dfr.html">map_dfr</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="va">`[`</span>, <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"name"</span>, <span class="st">"gender"</span>, <span class="st">"born"</span><span class="op">)</span><span class="op">)</span> </span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code># A tibble: 30 × 3
name gender born
<chr> <chr> <chr>
1 Theon Greyjoy Male "In 278 AC or 279 AC, at Pyke"
2 Tyrion Lannister Male "In 273 AC, at Casterly Rock"
3 Victarion Greyjoy Male "In 268 AC or before, at Pyke"
4 Will Male ""
5 Areo Hotah Male "In 257 AC or before, at Norvos"
6 Chett Male "At Hag's Mire"
7 Cressen Male "In 219 AC or 220 AC"
8 Arianne Martell Female "In 276 AC, at Sunspear"
9 Daenerys Targaryen Female "In 284 AC, at Dragonstone"
10 Davos Seaworth Male "In 260 AC or before, at King's Landing"
# ℹ 20 more rows</code></pre>
</div>
<div class="sourceCode" id="cb76" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="co"># Equivalent to</span></span>
<span><span class="fu">purrr</span><span class="fu">::</span><span class="fu"><a href="https://purrr.tidyverse.org/reference/map.html">map</a></span><span class="op">(</span><span class="va">got_chars</span>, <span class="va">`[`</span>, <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"name"</span>, <span class="st">"gender"</span>, <span class="st">"born"</span><span class="op">)</span><span class="op">)</span> <span class="op">|></span></span>
<span> <span class="fu">dplyr</span><span class="fu">::</span><span class="fu"><a href="https://dplyr.tidyverse.org/reference/bind_rows.html">bind_rows</a></span><span class="op">(</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre data-code-line-numbers=""><code># A tibble: 30 × 3
name gender born
<chr> <chr> <chr>
1 Theon Greyjoy Male "In 278 AC or 279 AC, at Pyke"
2 Tyrion Lannister Male "In 273 AC, at Casterly Rock"
3 Victarion Greyjoy Male "In 268 AC or before, at Pyke"
4 Will Male ""
5 Areo Hotah Male "In 257 AC or before, at Norvos"
6 Chett Male "At Hag's Mire"
7 Cressen Male "In 219 AC or 220 AC"
8 Arianne Martell Female "In 276 AC, at Sunspear"
9 Daenerys Targaryen Female "In 284 AC, at Dragonstone"
10 Davos Seaworth Male "In 260 AC or before, at King's Landing"
# ℹ 20 more rows</code></pre>
</div>
</div>
<p>If we want to more generally convert the entire data set to a data frame, we can use a couple of handy functions to do that:</p>
<ul>
<li>
<code><a href="https://purrr.tidyverse.org/reference/transpose.html">purrr::transpose</a></code> transposes a list, so that x[[1]][[2]] becomes x[[2]][[1]]. This turns the list into a set of columns.</li>
<li>
<code><a href="https://tibble.tidyverse.org/reference/as_tibble.html">tibble::as_tibble</a></code> turns an object into a tibble. This creates a rectangular, data frame like structure</li>
<li>
<code>purrr::unnest</code> takes columns and “ungroups” them, so that each entry in the sub-lists of the column gets a row in the data frame. Here, I’ve used this to unwrap lists that are all single items so that we can see some of the data.</li>
</ul>
<div class="cell">
<div class="sourceCode" id="cb78" data-source-line-numbers="nil" data-code-line-numbers="nil"><pre class="downlit sourceCode r code-with-copy"><code class="sourceCode R"><span><span class="va">got_df</span> <span class="op"><-</span> <span class="va">got_chars</span> <span class="op">|></span></span>
<span> <span class="fu"><a href="https://purrr.tidyverse.org/reference/transpose.html">transpose</a></span><span class="op">(</span><span class="op">)</span> <span class="op">|></span></span>
<span> <span class="fu">as_tibble</span><span class="op">(</span><span class="op">)</span> <span class="op">|></span></span>
<span> <span class="fu">unnest</span><span class="op">(</span><span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"url"</span>, <span class="st">"id"</span>, <span class="st">"name"</span>, <span class="st">"gender"</span>, </span>
<span> <span class="st">"culture"</span>, <span class="st">"born"</span>, <span class="st">"died"</span>, <span class="st">"alive"</span>, </span>
<span> <span class="st">"father"</span>, <span class="st">"mother"</span>, <span class="st">"spouse"</span><span class="op">)</span><span class="op">)</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div class="cell">
<div class="cell-output-display">
<div style="border: 1px solid #ddd; padding: 0px; overflow-y: scroll; height:600px; ">
<table class="table table-sm table-striped small" data-quarto-postprocess="true">
<thead><tr class="header">
<th data-quarto-table-cell-role="th" style="text-align: left; position: sticky; top: 0; background-color: #FFFFFF;">url</th>
<th data-quarto-table-cell-role="th" style="text-align: right; position: sticky; top: 0; background-color: #FFFFFF;">id</th>
<th data-quarto-table-cell-role="th" style="text-align: left; position: sticky; top: 0; background-color: #FFFFFF;">name</th>
<th data-quarto-table-cell-role="th" style="text-align: left; position: sticky; top: 0; background-color: #FFFFFF;">gender</th>
<th data-quarto-table-cell-role="th" style="text-align: left; position: sticky; top: 0; background-color: #FFFFFF;">culture</th>