-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathls13_list-columns.html
More file actions
954 lines (869 loc) · 36.8 KB
/
Copy pathls13_list-columns.html
File metadata and controls
954 lines (869 loc) · 36.8 KB
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>List columns</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/flatly.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 60px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 65px;
margin-top: -65px;
}
.section h2 {
padding-top: 65px;
margin-top: -65px;
}
.section h3 {
padding-top: 65px;
margin-top: -65px;
}
.section h4 {
padding-top: 65px;
margin-top: -65px;
}
.section h5 {
padding-top: 65px;
margin-top: -65px;
}
.section h6 {
padding-top: 65px;
margin-top: -65px;
}
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #ffffff;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">purrr tutorial</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Lessons and examples</a>
</li>
<li>
<a href="more-resources.html">More resources</a>
</li>
<li>
<a href="talks.html">Talks</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="about.html">About</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">List columns</h1>
</div>
<p>Data frames are a fantastic data structure for data analysis. We usually think of them as a data receptacle for several atomic vectors with a common length and with a notion of “observation”, i.e. the i-th value of each atomic vector is related to all the other i-th values.</p>
<p>But data frame are not limited to atomic vectors. They can host general vectors, i.e. <em>lists</em> as well. This is what I call a <strong>list-column</strong>.</p>
<p>List-columns and the data frame that hosts them require some special handling. In particular, it is highly advantageous if the data frame is a <a href="https://github.com/tidyverse/tibble#readme">tibble</a>, which anticipates list-columns. To work comfortably with list-columns, you need to develop techniques to:</p>
<ul>
<li><strong>Inspect</strong>. What have I created?</li>
<li><strong>Index</strong>. How do I pull out specific bits by name or position?</li>
<li><strong>Compute</strong>. How do I operate on my list-column to make another vector or list-column?</li>
<li><strong>Simplify</strong>. How do I get rid of this list-column and back to a normal data frame?</li>
</ul>
<p>The purrr package and all the techniques depicted in the other lessons come into heavy play here. This is a collection of worked examples that show these techniques applied specifically to list-columns.</p>
<div id="regex-and-trump-tweets" class="section level2">
<h2>Regex and Trump tweets</h2>
<div id="load-packages" class="section level3">
<h3>Load packages</h3>
<pre class="r"><code>library(tidyverse)
library(lubridate)
library(here)</code></pre>
</div>
<div id="bring-tweets-in" class="section level3">
<h3>Bring tweets in</h3>
<p>Working with the same 7 tweets as <a href="ls08_trump-tweets.html">Trump Android words</a> lesson. Go there for the rationale for choosing these 7 tweets.</p>
<pre class="r"><code>tb_raw <- read_csv(here("talks", "trump-tweets.csv"))
#> Parsed with column specification:
#> cols(
#> tweet = col_character(),
#> source = col_character(),
#> created = col_datetime(format = "")
#> )</code></pre>
</div>
<div id="create-a-list-column-of-trump-android-words" class="section level3">
<h3>Create a list-column of Trump Android words</h3>
<p>Clean a variable and create a list-column:</p>
<ul>
<li><code>source</code> comes in an unfriendly form. Simplify to convey if tweet came from Android or iPhone.</li>
<li><code>twords</code> are what we’ll call the “Trump Android words”. See <a href="ls08_trump-tweets.html">Trump Android words</a> lesson for backstory. <strong>This is a list-column!</strong></li>
</ul>
<pre class="r"><code>source_regex <- "android|iphone"
tword_regex <- "badly|crazy|weak|spent|strong|dumb|joke|guns|funny|dead"
tb <- tb_raw %>%
mutate(source = str_extract(source, source_regex),
twords = str_extract_all(tweet, tword_regex))</code></pre>
</div>
<div id="derive-new-variables" class="section level3">
<h3>Derive new variables</h3>
<p>Add variables, two of which are based on the <code>twords</code> list-column.</p>
<ul>
<li><code>n</code>: How many twords are in the tweet?</li>
<li><code>hour</code>: At which hour of the day was the tweet?</li>
<li><code>start</code>: Start character of each tword.</li>
</ul>
<pre class="r"><code>tb <- tb %>%
mutate(n = lengths(twords),
hour = hour(created),
start = gregexpr(tword_regex, tweet))</code></pre>
</div>
<div id="use-regular-data-manipulation-toolkit" class="section level3">
<h3>Use regular data manipulation toolkit</h3>
<p>Let’s isolate tweets created before 2pm, containing 1 or 2 twords, in which there’s an tword that starts within the first 30 characters.</p>
<pre class="r"><code>tb %>%
filter(hour < 14,
between(n, 1, 2),
between(map_int(start, min), 0, 30))
#> # A tibble: 1 x 7
#> tweet source created twords n hour start
#> <chr> <chr> <dttm> <list> <int> <int> <lis>
#> 1 Bernie Sanders star… android 2016-07-24 11:25:06 <chr … 2 11 <int…</code></pre>
<p>Let’s isolate tweets that contain both the twords “strong” and “weak”.</p>
<pre class="r"><code>tb %>%
filter(map_lgl(twords, ~ all(c("strong", "weak") %in% .x)))
#> # A tibble: 2 x 7
#> tweet source created twords n hour start
#> <chr> <chr> <dttm> <list> <int> <int> <lis>
#> 1 Bernie Sanders star… android 2016-07-24 11:25:06 <chr … 2 11 <int…
#> 2 Crooked Hillary Cli… android 2016-07-06 04:36:31 <chr … 2 4 <int…</code></pre>
</div>
</div>
<div id="json-from-an-api-and-game-of-thrones" class="section level2">
<h2>JSON from an API and Game of Thrones</h2>
<div id="load-packages-1" class="section level3">
<h3>Load packages</h3>
<pre class="r"><code>library(repurrrsive)
library(tidyverse)
library(httr)
library(here)</code></pre>
</div>
<div id="call-the-api-of-ice-and-fire" class="section level3">
<h3>Call the API of Ice and Fire</h3>
<p>Here’s a simplified version of how we obtained the data on the Game of Thrones POV characters. This data appears as a more processed list in the <a href="https://cran.r-project.org/package=repurrrsive">repurrrsive</a> package.</p>
<ul>
<li>Get character IDs from repurrrsive. <em>cheating a little, humor me</em></li>
<li>Put IDs and character names in a tibble.</li>
</ul>
<pre class="r"><code>pov <- set_names(map_int(got_chars, "id"),
map_chr(got_chars, "name"))
tail(pov, 5)
#> Melisandre Merrett Frey Quentyn Martell Samwell Tarly
#> 743 751 844 954
#> Sansa Stark
#> 957
ice <- pov %>%
enframe(value = "id")
ice
#> # A tibble: 30 x 2
#> name id
#> <chr> <int>
#> 1 Theon Greyjoy 1022
#> 2 Tyrion Lannister 1052
#> 3 Victarion Greyjoy 1074
#> 4 Will 1109
#> 5 Areo Hotah 1166
#> 6 Chett 1267
#> 7 Cressen 1295
#> 8 Arianne Martell 130
#> 9 Daenerys Targaryen 1303
#> 10 Davos Seaworth 1319
#> # … with 20 more rows</code></pre>
<p>Request info for each character and store what comes back – whatever that may be – in the list-column <code>stuff</code>.</p>
<pre class="r"><code>ice_and_fire_url <- "https://anapioficeandfire.com/"
if (file.exists(here("talks", "ice.rds"))) {
ice <- readRDS(here("talks", "ice.rds"))
} else {
ice <- ice %>%
mutate(
response = map(id,
~ GET(ice_and_fire_url,
path = c("api", "characters", .x))),
stuff = map(response, ~ content(.x, as = "parsed",
simplifyVector = TRUE))
) %>%
select(-id, -response)
saveRDS(ice, here("talks", "ice.rds"))
}
ice
#> # A tibble: 29 x 2
#> name stuff
#> <chr> <list>
#> 1 Theon Greyjoy <named list [16]>
#> 2 Tyrion Lannister <named list [16]>
#> 3 Victarion Greyjoy <named list [16]>
#> 4 Will <named list [16]>
#> 5 Areo Hotah <named list [16]>
#> 6 Chett <named list [16]>
#> 7 Cressen <named list [16]>
#> 8 Arianne Martell <named list [16]>
#> 9 Daenerys Targaryen <named list [16]>
#> 10 Davos Seaworth <named list [16]>
#> # … with 19 more rows</code></pre>
<p>Let’s switch to a nicer version of <code>ice</code>, based on the list in repurrrsive, because it already has books and houses replaced with names instead of URLs.</p>
<pre class="r"><code>ice2 <- tibble(
name = map_chr(got_chars, "name"),
stuff = got_chars
)
ice2
#> # A tibble: 30 x 2
#> name stuff
#> <chr> <list>
#> 1 Theon Greyjoy <named list [18]>
#> 2 Tyrion Lannister <named list [18]>
#> 3 Victarion Greyjoy <named list [18]>
#> 4 Will <named list [18]>
#> 5 Areo Hotah <named list [18]>
#> 6 Chett <named list [18]>
#> 7 Cressen <named list [18]>
#> 8 Arianne Martell <named list [18]>
#> 9 Daenerys Targaryen <named list [18]>
#> 10 Davos Seaworth <named list [18]>
#> # … with 20 more rows</code></pre>
<p>Inspect the list-column.</p>
<pre class="r"><code>str(ice2$stuff[[9]], max.level = 1)
#> List of 18
#> $ url : chr "https://www.anapioficeandfire.com/api/characters/1303"
#> $ id : int 1303
#> $ name : chr "Daenerys Targaryen"
#> $ gender : chr "Female"
#> $ culture : chr "Valyrian"
#> $ born : chr "In 284 AC, at Dragonstone"
#> $ died : chr ""
#> $ alive : logi TRUE
#> $ titles : chr [1:5] "Queen of the Andals and the Rhoynar and the First Men, Lord of the Seven Kingdoms" "Khaleesi of the Great Grass Sea" "Breaker of Shackles/Chains" "Queen of Meereen" ...
#> $ aliases : chr [1:11] "Dany" "Daenerys Stormborn" "The Unburnt" "Mother of Dragons" ...
#> $ father : chr ""
#> $ mother : chr ""
#> $ spouse : chr "https://www.anapioficeandfire.com/api/characters/1346"
#> $ allegiances: chr "House Targaryen of King's Landing"
#> $ books : chr "A Feast for Crows"
#> $ povBooks : chr [1:4] "A Game of Thrones" "A Clash of Kings" "A Storm of Swords" "A Dance with Dragons"
#> $ tvSeries : chr [1:6] "Season 1" "Season 2" "Season 3" "Season 4" ...
#> $ playedBy : chr "Emilia Clarke"
# if (interactive()) {
# listviewer::jsonedit(ice2$stuff[[2]], mode = "view", width = 500, height = 530)
# }</code></pre>
</div>
<div id="use-regular-data-manipulation-toolkit-1" class="section level3">
<h3>Use regular data manipulation toolkit</h3>
<p>Form a sentence of the form “NAME was born AT THIS TIME, IN THIS PLACE” by digging info out of the <code>stuff</code> list-column and placing into a string template. No list-columns left!</p>
<pre class="r"><code>template <- "${name} was born ${born}."
birth_announcements <- ice2 %>%
mutate(birth = map_chr(stuff, str_interp, string = template)) %>%
select(-stuff)
birth_announcements
#> # A tibble: 30 x 2
#> name birth
#> <chr> <chr>
#> 1 Theon Greyjoy Theon Greyjoy was born In 278 AC or 279 AC, at Pyke.
#> 2 Tyrion Lannister Tyrion Lannister was born In 273 AC, at Casterly Rock.
#> 3 Victarion Greyjoy Victarion Greyjoy was born In 268 AC or before, at Py…
#> 4 Will Will was born .
#> 5 Areo Hotah Areo Hotah was born In 257 AC or before, at Norvos.
#> 6 Chett Chett was born At Hag's Mire.
#> 7 Cressen Cressen was born In 219 AC or 220 AC.
#> 8 Arianne Martell Arianne Martell was born In 276 AC, at Sunspear.
#> 9 Daenerys Targary… Daenerys Targaryen was born In 284 AC, at Dragonstone.
#> 10 Davos Seaworth Davos Seaworth was born In 260 AC or before, at King'…
#> # … with 20 more rows</code></pre>
<p>Extract each character’s house allegiances. Keep only those with more than one allegiance. Then unnest to explode the <code>houses</code> list-column and get a tibble with one row per character * house combination. No list-columns left!</p>
<pre class="r"><code>allegiances <- ice2 %>%
transmute(name,
houses = map(stuff, "allegiances")) %>%
filter(lengths(houses) > 1) %>%
unnest(houses)
allegiances
#> # A tibble: 15 x 2
#> name houses
#> <chr> <chr>
#> 1 Davos Seaworth House Baratheon of Dragonstone
#> 2 Davos Seaworth House Seaworth of Cape Wrath
#> 3 Asha Greyjoy House Greyjoy of Pyke
#> 4 Asha Greyjoy House Ironmaker
#> 5 Barristan Selmy House Selmy of Harvest Hall
#> 6 Barristan Selmy House Targaryen of King's Landing
#> 7 Brienne of Tarth House Baratheon of Storm's End
#> 8 Brienne of Tarth House Stark of Winterfell
#> 9 Brienne of Tarth House Tarth of Evenfall Hall
#> 10 Catelyn Stark House Stark of Winterfell
#> 11 Catelyn Stark House Tully of Riverrun
#> 12 Jon Connington House Connington of Griffin's Roost
#> 13 Jon Connington House Targaryen of King's Landing
#> 14 Sansa Stark House Baelish of Harrenhal
#> 15 Sansa Stark House Stark of Winterfell</code></pre>
</div>
</div>
<div id="aliases-and-allegiances-of-game-of-thrones-characters" class="section level2">
<h2>Aliases and allegiances of Game of Thrones characters</h2>
<div id="load-packages-2" class="section level3">
<h3>Load packages</h3>
<pre class="r"><code>library(tidyverse)
library(repurrrsive)</code></pre>
</div>
</div>
<div id="lists-as-variables-in-a-data-frame" class="section level2">
<h2>Lists as variables in a data frame</h2>
<p>One row per GoT character. List columns for aliases and allegiances.</p>
<pre class="r"><code>x <- tibble(
name = got_chars %>% map_chr("name"),
aliases = got_chars %>% map("aliases"),
allegiances = got_chars %>% map("allegiances")
)
x
#> # A tibble: 30 x 3
#> name aliases allegiances
#> <chr> <list> <list>
#> 1 Theon Greyjoy <chr [4]> <chr [1]>
#> 2 Tyrion Lannister <chr [11]> <chr [1]>
#> 3 Victarion Greyjoy <chr [1]> <chr [1]>
#> 4 Will <chr [1]> <NULL>
#> 5 Areo Hotah <chr [1]> <chr [1]>
#> 6 Chett <chr [1]> <NULL>
#> 7 Cressen <chr [1]> <NULL>
#> 8 Arianne Martell <chr [1]> <chr [1]>
#> 9 Daenerys Targaryen <chr [11]> <chr [1]>
#> 10 Davos Seaworth <chr [5]> <chr [2]>
#> # … with 20 more rows
#View(x)</code></pre>
<p>What if we only care about characters with a “Lannister” alliance? Practice operating on a list-column.</p>
<pre class="r"><code>x %>%
mutate(lannister = map(allegiances, str_detect, pattern = "Lannister"),
lannister = map_lgl(lannister, any))
#> # A tibble: 30 x 4
#> name aliases allegiances lannister
#> <chr> <list> <list> <lgl>
#> 1 Theon Greyjoy <chr [4]> <chr [1]> FALSE
#> 2 Tyrion Lannister <chr [11]> <chr [1]> TRUE
#> 3 Victarion Greyjoy <chr [1]> <chr [1]> FALSE
#> 4 Will <chr [1]> <NULL> FALSE
#> 5 Areo Hotah <chr [1]> <chr [1]> FALSE
#> 6 Chett <chr [1]> <NULL> FALSE
#> 7 Cressen <chr [1]> <NULL> FALSE
#> 8 Arianne Martell <chr [1]> <chr [1]> FALSE
#> 9 Daenerys Targaryen <chr [11]> <chr [1]> FALSE
#> 10 Davos Seaworth <chr [5]> <chr [2]> FALSE
#> # … with 20 more rows</code></pre>
<p>Keep only the Lannisters and Starks allegiances. You can use <code>filter()</code> with list-columns, but you will need to <code>map()</code> to list-ize your operation. Once I’ve got the characters I want, I drop <code>allegiances</code> and use <code>unnest()</code> to get back to a simple data frame with no list columns.</p>
<pre class="r"><code>x %>%
filter(allegiances %>%
map(str_detect, "Lannister|Stark") %>%
map_lgl(any)) %>%
select(-allegiances) %>%
filter(lengths(aliases) > 0) %>%
unnest(aliases) %>%
print(n = Inf)
#> # A tibble: 57 x 2
#> name aliases
#> <chr> <chr>
#> 1 Tyrion Lannister The Imp
#> 2 Tyrion Lannister Halfman
#> 3 Tyrion Lannister The boyman
#> 4 Tyrion Lannister Giant of Lannister
#> 5 Tyrion Lannister Lord Tywin's Doom
#> 6 Tyrion Lannister Lord Tywin's Bane
#> 7 Tyrion Lannister Yollo
#> 8 Tyrion Lannister Hugor Hill
#> 9 Tyrion Lannister No-Nose
#> 10 Tyrion Lannister Freak
#> 11 Tyrion Lannister Dwarf
#> 12 Arya Stark Arya Horseface
#> 13 Arya Stark Arya Underfoot
#> 14 Arya Stark Arry
#> 15 Arya Stark Lumpyface
#> 16 Arya Stark Lumpyhead
#> 17 Arya Stark Stickboy
#> 18 Arya Stark Weasel
#> 19 Arya Stark Nymeria
#> 20 Arya Stark Squan
#> 21 Arya Stark Saltb
#> 22 Arya Stark Cat of the Canaly
#> 23 Arya Stark Bets
#> 24 Arya Stark The Blind Girh
#> 25 Arya Stark The Ugly Little Girl
#> 26 Arya Stark Mercedenl
#> 27 Arya Stark Mercye
#> 28 Brandon Stark Bran
#> 29 Brandon Stark Bran the Broken
#> 30 Brandon Stark The Winged Wolf
#> 31 Brienne of Tarth The Maid of Tarth
#> 32 Brienne of Tarth Brienne the Beauty
#> 33 Brienne of Tarth Brienne the Blue
#> 34 Catelyn Stark Catelyn Tully
#> 35 Catelyn Stark Lady Stoneheart
#> 36 Catelyn Stark The Silent Sistet
#> 37 Catelyn Stark Mother Mercilesr
#> 38 Catelyn Stark The Hangwomans
#> 39 Eddard Stark Ned
#> 40 Eddard Stark The Ned
#> 41 Eddard Stark The Quiet Wolf
#> 42 Jaime Lannister The Kingslayer
#> 43 Jaime Lannister The Lion of Lannister
#> 44 Jaime Lannister The Young Lion
#> 45 Jaime Lannister Cripple
#> 46 Jon Snow Lord Snow
#> 47 Jon Snow Ned Stark's Bastard
#> 48 Jon Snow The Snow of Winterfell
#> 49 Jon Snow The Crow-Come-Over
#> 50 Jon Snow The 998th Lord Commander of the Night's Watch
#> 51 Jon Snow The Bastard of Winterfell
#> 52 Jon Snow The Black Bastard of the Wall
#> 53 Jon Snow Lord Crow
#> 54 Kevan Lannister ""
#> 55 Sansa Stark Little bird
#> 56 Sansa Stark Alayne Stone
#> 57 Sansa Stark Jonquil</code></pre>
</div>
<div id="nested-data-frame-modelling-and-gapminder" class="section level2">
<h2>Nested data frame, modelling, and Gapminder</h2>
<p>Another version of this same example is here:</p>
<p><a href="http://r4ds.had.co.nz/many-models.html" class="uri">http://r4ds.had.co.nz/many-models.html</a></p>
<p><em>mostly code at this point, more words needed</em></p>
<div id="load-packages-3" class="section level3">
<h3>Load packages</h3>
<pre class="r"><code>library(tidyverse)
library(gapminder)
library(broom)</code></pre>
</div>
<div id="hello-again-gapminder" class="section level3">
<h3>Hello, again, Gapminder</h3>
<pre class="r"><code>gapminder %>%
ggplot(aes(year, lifeExp, group = country)) +
geom_line(alpha = 1/3)</code></pre>
<p><img src="ls13_list-columns_files/figure-html/unnamed-chunk-22-1.png" width="672" /></p>
<p>What if we fit a line to each country?</p>
<pre class="r"><code>gapminder %>%
ggplot(aes(year, lifeExp, group = country)) +
geom_line(stat = "smooth", method = "lm",
alpha = 1/3, se = FALSE, colour = "black")</code></pre>
<p><img src="ls13_list-columns_files/figure-html/unnamed-chunk-23-1.png" width="672" /></p>
<p>What if you actually want those fits? To access estimates, p-values, etc. In that case, you need to fit them yourself. How to do that?</p>
<ul>
<li>Put the variables needed for country-specific models into nested dataframe. In a <strong>list-column</strong>!</li>
<li>Use the usual “map inside mutate”, possibly with the broom package, to pull interesting information out of the 142 fitted linear models.</li>
</ul>
</div>
<div id="nested-data-frame" class="section level3">
<h3>Nested data frame</h3>
<p>Nest the data frames, i.e. get one meta-row per country:</p>
<pre class="r"><code>gap_nested <- gapminder %>%
group_by(country) %>%
nest()
gap_nested
#> # A tibble: 142 x 2
#> # Groups: country [142]
#> country data
#> <fct> <list<df[,5]>>
#> 1 Afghanistan [12 × 5]
#> 2 Albania [12 × 5]
#> 3 Algeria [12 × 5]
#> 4 Angola [12 × 5]
#> 5 Argentina [12 × 5]
#> 6 Australia [12 × 5]
#> 7 Austria [12 × 5]
#> 8 Bahrain [12 × 5]
#> 9 Bangladesh [12 × 5]
#> 10 Belgium [12 × 5]
#> # … with 132 more rows
gap_nested$data[[1]]
#> # A tibble: 12 x 5
#> continent year lifeExp pop gdpPercap
#> <fct> <int> <dbl> <int> <dbl>
#> 1 Asia 1952 28.8 8425333 779.
#> 2 Asia 1957 30.3 9240934 821.
#> 3 Asia 1962 32.0 10267083 853.
#> 4 Asia 1967 34.0 11537966 836.
#> 5 Asia 1972 36.1 13079460 740.
#> 6 Asia 1977 38.4 14880372 786.
#> 7 Asia 1982 39.9 12881816 978.
#> 8 Asia 1987 40.8 13867957 852.
#> 9 Asia 1992 41.7 16317921 649.
#> 10 Asia 1997 41.8 22227415 635.
#> 11 Asia 2002 42.1 25268405 727.
#> 12 Asia 2007 43.8 31889923 975.</code></pre>
<p><em>Compare/contrast to a data frame grouped by country (dplyr-style) or split on country (base)</em>.</p>
</div>
<div id="fit-models-extract-results" class="section level3">
<h3>Fit models, extract results</h3>
<p>Fit a model for each country.</p>
<pre class="r"><code>gap_fits <- gap_nested %>%
mutate(fit = map(data, ~ lm(lifeExp ~ year, data = .x)))</code></pre>
<p>Look at one fitted model, for concreteness.</p>
<pre class="r"><code>gap_fits %>% tail(3)
#> # A tibble: 3 x 3
#> # Groups: country [142]
#> country data fit
#> <fct> <list<df[,5]>> <list>
#> 1 Yemen, Rep. [12 × 5] <lm>
#> 2 Zambia [12 × 5] <lm>
#> 3 Zimbabwe [12 × 5] <lm>
canada <- which(gap_fits$country == "Canada")
summary(gap_fits$fit[[canada]])
#>
#> Call:
#> lm(formula = lifeExp ~ year, data = .x)
#>
#> Residuals:
#> Min 1Q Median 3Q Max
#> -0.3812 -0.1368 -0.0471 0.2481 0.3157
#>
#> Coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -3.583e+02 8.252e+00 -43.42 1.01e-12 ***
#> year 2.189e-01 4.169e-03 52.50 1.52e-13 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 0.2492 on 10 degrees of freedom
#> Multiple R-squared: 0.9964, Adjusted R-squared: 0.996
#> F-statistic: 2757 on 1 and 10 DF, p-value: 1.521e-13</code></pre>
<p>Let’s get all the r-squared values!</p>
<pre class="r"><code>gap_fits %>%
mutate(rsq = map_dbl(fit, ~ summary(.x)[["r.squared"]])) %>%
arrange(rsq)
#> # A tibble: 142 x 4
#> # Groups: country [142]
#> country data fit rsq
#> <fct> <list<df[,5]>> <list> <dbl>
#> 1 Rwanda [12 × 5] <lm> 0.0172
#> 2 Botswana [12 × 5] <lm> 0.0340
#> 3 Zimbabwe [12 × 5] <lm> 0.0562
#> 4 Zambia [12 × 5] <lm> 0.0598
#> 5 Swaziland [12 × 5] <lm> 0.0682
#> 6 Lesotho [12 × 5] <lm> 0.0849
#> 7 Cote d'Ivoire [12 × 5] <lm> 0.283
#> 8 South Africa [12 × 5] <lm> 0.312
#> 9 Uganda [12 × 5] <lm> 0.342
#> 10 Congo, Dem. Rep. [12 × 5] <lm> 0.348
#> # … with 132 more rows</code></pre>
<p>Let’s use a function from broom to get the usual coefficient table from <code>summary.lm()</code> but in a friendlier form for downstream work.</p>
<pre class="r"><code>library(broom)
gap_fits %>%
mutate(coef = map(fit, tidy)) %>%
unnest(coef)
#> # A tibble: 284 x 8
#> # Groups: country [142]
#> country data fit term estimate std.error statistic p.value
#> <fct> <list<df[> <lis> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 Afghanis… [12 × 5] <lm> (Inter… -5.08e+2 40.5 -12.5 1.93e- 7
#> 2 Afghanis… [12 × 5] <lm> year 2.75e-1 0.0205 13.5 9.84e- 8
#> 3 Albania [12 × 5] <lm> (Inter… -5.94e+2 65.7 -9.05 3.94e- 6
#> 4 Albania [12 × 5] <lm> year 3.35e-1 0.0332 10.1 1.46e- 6
#> 5 Algeria [12 × 5] <lm> (Inter… -1.07e+3 43.8 -24.4 3.07e-10
#> 6 Algeria [12 × 5] <lm> year 5.69e-1 0.0221 25.7 1.81e-10
#> 7 Angola [12 × 5] <lm> (Inter… -3.77e+2 46.6 -8.08 1.08e- 5
#> 8 Angola [12 × 5] <lm> year 2.09e-1 0.0235 8.90 4.59e- 6
#> 9 Argentina [12 × 5] <lm> (Inter… -3.90e+2 9.68 -40.3 2.14e-12
#> 10 Argentina [12 × 5] <lm> year 2.32e-1 0.00489 47.4 4.22e-13
#> # … with 274 more rows</code></pre>
</div>
</div>
<i class="fab fa-creative-commons fa-2x"></i><i class="fab fa-creative-commons-by fa-2x"></i><i class="fab fa-creative-commons-sa fa-2x"></i>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open')
});
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2,h3",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>