Repository navigation
Expand file tree
/
Copy pathindex.xml
More file actions
3171 lines (3040 loc) · 167 KB
/
Copy pathindex.xml
File metadata and controls
3171 lines (3040 loc) · 167 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
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
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Tanner Koomar</title>
<link>/</link>
<atom:link href="/index.xml" rel="self" type="application/rss+xml" />
<description>Tanner Koomar</description>
<generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><copyright>2021</copyright><lastBuildDate>Thu, 28 Jun 2018 00:00:00 +0100</lastBuildDate>
<image>
<url>img/map[gravatar:%!s(bool=false) shape:square]</url>
<title>Tanner Koomar</title>
<link>/</link>
</image>
<item>
<title>Estimating the Prevalence and Genetic Risk Mechanisms of ARFID in a Large Autism Cohort</title>
<link>/publication/2021-arfid-paper/</link>
<pubDate>Fri, 09 Jul 2021 00:00:00 +0000</pubDate>
<guid>/publication/2021-arfid-paper/</guid>
<description></description>
</item>
<item>
<title>Palmer Penguins</title>
<link>/post/tt-palmer-penguins/</link>
<pubDate>Mon, 27 Jul 2020 00:00:00 +0000</pubDate>
<guid>/post/tt-palmer-penguins/</guid>
<description>
<div id="TOC">
<ul>
<li><a href="#load-packages">Load Packages</a></li>
<li><a href="#read-in-penguin-diagram">Read in penguin diagram</a></li>
<li><a href="#summarize-data">Summarize data</a></li>
<li><a href="#simple-plot">Simple plot</a></li>
<li><a href="#customize-plot">Customize Plot</a></li>
</ul>
</div>
<div id="load-packages" class="section level2">
<h2>Load Packages</h2>
<pre class="r"><code>library(tidyverse)
library(palmerpenguins)
library(ggnewscale)
library(sf)
library(patchwork)
library(showtext)</code></pre>
</div>
<div id="read-in-penguin-diagram" class="section level2">
<h2>Read in penguin diagram</h2>
<p>This is a rough draft of a heatmap diagram specifically for the <a href="https://allisonhorst.github.io/palmerpenguins/"><code>{palmerpenguins}</code></a> dataset, and at the time of this writing is living on a development branch of the <em>very</em> nascent <a href="https://tkoomar.github.io/sffs/">Simple Features For Science <code>{sffs}</code> warehouse / package</a>.</p>
<pre class="r"><code>sf_palmer &lt;- read_sf(&quot;https://raw.githubusercontent.com/tkoomar/sffs/palmer/data-raw/sf_palmer/sf_palmer.geojson&quot;)
print(sf_palmer)</code></pre>
<pre><code>## Simple feature collection with 9 features and 1 field
## geometry type: POLYGON
## dimension: XY
## bbox: xmin: 0.159483 ymin: -1.063218 xmax: 1.369025 ymax: 0.979735
## CRS: 4326
## # A tibble: 9 x 2
## id geometry
## &lt;chr&gt; &lt;POLYGON [°]&gt;
## 1 background ((1.037073 -0.844313, 1.037073 -0.844313, 1.037321 -0.843974, …
## 2 foot ((1.02272 -0.868436, 1.022712 -0.868446, 1.022607 -0.868572, 1…
## 3 flipper_lengt… ((0.804533 0.049629, 0.804448 0.049715, 0.804276 0.049887, 0.8…
## 4 bill_length_mm ((1.260757 0.847204, 1.26037 0.847223, 1.2596 0.847262, 1.2588…
## 5 bill_depth_mm ((1.260757 0.847204, 1.26037 0.847223, 1.2596 0.847262, 1.2588…
## 6 face ((1.174673 0.856284, 1.174691 0.856296, 1.174724 0.856322, 1.1…
## 7 body_mass_g ((0.597523 0.068709, 0.597514 0.068705, 0.597494 0.068696, 0.5…
## 8 eye ((0.93493 0.813604, 0.934965 0.813629, 0.935024 0.813671, 0.93…
## 9 pupil ((0.940806 0.7871717, 0.940859 0.787341, 0.940897 0.787461, 0.…</code></pre>
<p>What does it look like? Let’s take a peak:</p>
<pre class="r"><code>ggplot(sf_palmer) +
geom_sf() +
theme_void()</code></pre>
<p><img src="./post/2020-07-27-tt-palmer-penguins/index_files/figure-html/unnamed-chunk-3-1.png" width="192" style="display: block; margin: auto;" /></p>
<p>They might not be the most dapper, but I find something about this penguin’s oddly lumpy form to be rather endearing.</p>
</div>
<div id="summarize-data" class="section level2">
<h2>Summarize data</h2>
<p>As alluded above, this week’s data comes from <a href="https://allisonhorst.github.io/palmerpenguins/"><code>{palmerpenguins}</code></a>, which is an alternative to the classic iris toy dataset, featureing everyones favorite antarctic flightless bird!</p>
<pre class="r"><code>head(penguins)</code></pre>
<pre><code>## # A tibble: 6 x 8
## species island bill_length_mm bill_depth_mm flipper_length_… body_mass_g sex
## &lt;fct&gt; &lt;fct&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;int&gt; &lt;fct&gt;
## 1 Adelie Torge… 39.1 18.7 181 3750 male
## 2 Adelie Torge… 39.5 17.4 186 3800 fema…
## 3 Adelie Torge… 40.3 18 195 3250 fema…
## 4 Adelie Torge… NA NA NA NA &lt;NA&gt;
## 5 Adelie Torge… 36.7 19.3 193 3450 fema…
## 6 Adelie Torge… 39.3 20.6 190 3650 male
## # … with 1 more variable: year &lt;int&gt;</code></pre>
<p>For this plot, we want one diagram/heatmap per species and sex. So, get the median value of each variable at that level. Note that because the scales of the different measurements are rather all over the place, we will first scale each so that values are expressed as standard deviations.</p>
<pre class="r"><code>penguins_scaled &lt;- penguins %&gt;%
drop_na() %&gt;%
mutate(across(where(is.numeric), ~scale(.x)[,1]))
penguins_scaled_summary &lt;- penguins_scaled %&gt;%
group_by(species, sex) %&gt;%
summarize(across(where(is.numeric), median),
.groups = &#39;keep&#39;)
penguins_scaled_summary_long &lt;- penguins_scaled_summary %&gt;%
pivot_longer(cols = 3:7,
names_to = &#39;id&#39;,
values_to = &#39;median_scaled_value&#39;) %&gt;%
mutate(sex = if_else(sex == &#39;female&#39;, &#39;♀&#39;, &#39;♂&#39;))
head(penguins_scaled_summary_long)</code></pre>
<pre><code>## # A tibble: 6 x 4
## # Groups: species, sex [2]
## species sex id median_scaled_value
## &lt;fct&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt;
## 1 Adelie ♀ bill_length_mm -1.28
## 2 Adelie ♀ bill_depth_mm 0.221
## 3 Adelie ♀ flipper_length_mm -0.925
## 4 Adelie ♀ body_mass_g -1.00
## 5 Adelie ♀ year -0.0517
## 6 Adelie ♂ bill_length_mm -0.620</code></pre>
<pre class="r"><code>background_fill_colors &lt;- c( background = &#39;black&#39;, foot = &#39;sienna1&#39;,
face = &#39;white&#39;,eye = &#39;coral1&#39;, pupil = &#39;black&#39;)
background_color_colors &lt;- c(background = &#39;black&#39;, foot = &#39;sienna4&#39;,
face = &#39;white&#39;, eye = &#39;black&#39;, pupil = &#39;black&#39;)
sf_background &lt;- sf_palmer %&gt;%
anti_join(penguins_scaled_summary_long) %&gt;%
## This first-draft of the diagram uses the same geometry for the bill length
## and bill width, so we will just visualize the depth here
filter(id != &#39;bill_length_mm&#39;) %&gt;%
mutate(id = as_factor(id))</code></pre>
<pre><code>## Joining, by = &quot;id&quot;</code></pre>
<pre class="r"><code>ggplot() +
geom_sf(data = sf_background,
aes(fill = id,
color = id)
) +
scale_fill_manual(values = background_fill_colors) +
scale_color_manual(values = background_color_colors)</code></pre>
<p><img src="./post/2020-07-27-tt-palmer-penguins/index_files/figure-html/unnamed-chunk-6-1.png" width="672" /></p>
<p>That looks a bit more like a proper penguin!</p>
<p>As you might be able to guess from the axis ticks on this plot, this diagram is actually a geographic map (of sorts). <code>{sffs}</code> takes advantage of the fact that ggplot will plot any arbitrary shape, so long as it can be expressed like a map (in this case, a <a href="https://r-spatial.github.io/sf/articles/sf1.html">simple features <code>{sf}</code></a> object).</p>
</div>
<div id="simple-plot" class="section level2">
<h2>Simple plot</h2>
<pre class="r"><code>penguin_plot &lt;- sf_palmer %&gt;%
inner_join(penguins_scaled_summary_long,
by = &#39;id&#39;) %&gt;%
ggplot() +
geom_sf(data = sf_background,
aes(fill = id,
color = id)
) +
scale_fill_manual(values = background_fill_colors,
guide = guide_none()) +
scale_color_manual(values = background_color_colors,
guide = guide_none()) +
new_scale_fill() +
new_scale_color() +
geom_sf(aes(fill = median_scaled_value), color = &#39;black&#39;) +
facet_grid(sex ~ species)
penguin_plot</code></pre>
<p><img src="./post/2020-07-27-tt-palmer-penguins/index_files/figure-html/unnamed-chunk-7-1.png" width="672" /></p>
<p>That isn’t particularly pretty. These penguins deserve to be seen in style, so let’s do some tweaking.</p>
</div>
<div id="customize-plot" class="section level2">
<h2>Customize Plot</h2>
<div id="better-color-scale" class="section level4">
<h4>Better color scale</h4>
<p>The human eye really isn’t good with continuous color scales. Let’s do a binned scale via <code>scale_fill_fermenter</code>, and make it a divergent once since we know we scaled our data. We will fit the limits to be symetric around 0.</p>
<pre class="r"><code>penguin_plot &lt;- penguin_plot +
scale_fill_fermenter(palette = &#39;Spectral&#39;,
limits = c(-1.5, 1.5),
n.breaks = 8,
labels = c(&#39;&lt; 1 SD smaller&#39;, &#39;&#39;, &#39;&#39;, &#39;average&#39;, &#39;&#39;, &#39;&#39;, &#39;&gt; 1 SD larger&#39;),
guide = guide_colorsteps(
title = element_blank(),
label.position = &#39;left&#39;,
barheight = 25,
barwidth = 1/2
)
) +
theme_void()
penguin_plot</code></pre>
<p><img src="./post/2020-07-27-tt-palmer-penguins/index_files/figure-html/unnamed-chunk-8-1.png" width="768" /></p>
<p>Looking pretty good, I think we just need to tweak the font face and size.</p>
</div>
<div id="font-face-and-size" class="section level4">
<h4>Font face and size</h4>
<pre class="r"><code>font_add_google(&quot;M PLUS Rounded 1c&quot;, &quot;M+300&quot;, regular.wt = 300)
font_add_google(&quot;Krona One&quot;, &quot;K1&quot;)
font_add_google(&quot;M PLUS Rounded 1c&quot;, &quot;M+100&quot;, regular.wt = 100)
showtext_auto()
penguin_plot &lt;- penguin_plot +
theme(
legend.position = &#39;left&#39;,
text = element_text(family = &#39;M+300&#39;, color = &#39;#434C5E&#39; ),
legend.text = element_text(size = 12, color = &#39;#4C566A&#39;),
strip.text.x = element_text( size = 25),
strip.text.y = element_text( size = 50, angle = 0)
)
penguin_plot</code></pre>
<p><img src="./post/2020-07-27-tt-palmer-penguins/index_files/figure-html/unnamed-chunk-9-1.png" width="768" /></p>
</div>
<div id="other-plot-colors" class="section level4">
<h4>Other Plot Colors</h4>
<pre class="r"><code>penguin_plot &lt;- penguin_plot +
theme(plot.background = element_rect(fill= alpha(&quot;#ECEFF4&quot;, 0.5),
color = NA),
panel.background = element_rect(fill = alpha(&quot;#E5E9F0&quot;, 0.5),
color = NA)
) </code></pre>
<pre class="r"><code>title_plot &lt;- ggplot() +
annotate(geom = &#39;text&#39;,
label = &#39;Palmer\nPenguins&#39;,
y = 2, x = 2,
size = 30,
color = &quot;#5E81AC&quot;,
family = &quot;K1&quot;,
hjust = 1,
vjust = 1,
lineheight = 0.55) +
coord_cartesian(xlim = c(0,2), ylim = c(0,2)) +
theme_void() +
theme(plot.caption = element_blank())
text_plot &lt;- ggplot() +
annotate(geom = &#39;text&#39;,
label = &#39;A real-world dataset gaining traction as an alternative to the classic iris dataset for demonstration and teaching.&#39; %&gt;% str_wrap(20),
y = 2, x = 0,
size = 9.8,
color = &quot;#8FBCBB&quot;,
family = &quot;M+300&quot;,
hjust = 0,
vjust = 1,
lineheight = 0.5) +
coord_cartesian(xlim = c(0,2), ylim = c(0,2)) +
geom_vline(xintercept = -0.1, color = &#39;#81A1C1&#39;, size = 1) +
labs(caption = &quot;A #TidyTuesday adventure\nDesign by @TannerKoomar\nArtwork by @allison_horst&quot;) +
theme_void() +
theme(plot.margin = margin(t = 20),
plot.caption = element_text(color = &quot;#8FBCBB&quot;,
family = &quot;M+300&quot;,
size = 11))
layout &lt;- &quot;
#111#
22233
###33
&quot;
penguin_plot + title_plot + text_plot +
plot_layout(design = layout,
widths = c(1, 10, 10, 10, 1),
heights = c(30, 12, 1/5)
) &amp;
theme(plot.background = element_rect(fill= &quot;#ECEFF4&quot;,
color = NA)
) </code></pre>
<p><img src="./post/2020-07-27-tt-palmer-penguins/index_files/figure-html/unnamed-chunk-11-1.png" width="768" /></p>
<pre class="r"><code>ggsave(&#39;featured.png&#39;, dpi = 144)</code></pre>
</div>
</div>
</description>
</item>
<item>
<title>Australian Pets</title>
<link>/post/2020-07-20-tt-australian-pets/</link>
<pubDate>Mon, 20 Jul 2020 00:00:00 +0000</pubDate>
<guid>/post/2020-07-20-tt-australian-pets/</guid>
<description>
<div id="TOC">
<ul>
<li><a href="#setup">Setup</a></li>
<li><a href="#peek-at-the-data">Peek at the data</a></li>
<li><a href="#get-a-map">Get a Map</a></li>
<li><a href="#combine-map-and-data">Combine Map and Data</a></li>
<li><a href="#combine-rehomed-and-released">Combine Rehomed and Released</a></li>
</ul>
</div>
<div id="setup" class="section level2">
<h2>Setup</h2>
<pre class="r"><code>library(tidyverse)
library(sf)
library(ggtext)
library(patchwork)
library(showtext)
font_add_google(&quot;Josefin Sans&quot;, &quot;Josefin Sans&quot;)
showtext_auto()
animal_outcomes &lt;- readr::read_csv(&#39;https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-07-21/animal_outcomes.csv&#39;) %&gt;%
filter(year &lt;= 2015)</code></pre>
</div>
<div id="peek-at-the-data" class="section level2">
<h2>Peek at the data</h2>
<pre class="r"><code>head(animal_outcomes)</code></pre>
<pre><code>## # A tibble: 6 x 12
## year animal_type outcome ACT NSW NT QLD SA TAS VIC WA
## &lt;dbl&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
## 1 1999 Dogs Reclai… 610 3140 205 1392 2329 516 7130 1
## 2 1999 Dogs Rehomed 1245 7525 526 5489 1105 480 4908 137
## 3 1999 Dogs Other 12 745 955 860 380 168 1001 6
## 4 1999 Dogs Euthan… 360 9221 9 9214 1701 599 5217 18
## 5 1999 Cats Reclai… 111 201 22 206 157 31 884 0
## 6 1999 Cats Rehomed 1442 3913 269 3901 1055 752 3768 62
## # … with 1 more variable: Total &lt;dbl&gt;</code></pre>
</div>
<div id="get-a-map" class="section level2">
<h2>Get a Map</h2>
<pre class="r"><code>au_sf &lt;- rnaturalearth::ne_states(country = &#39;Australia&#39;, returnclass = &#39;sf&#39;) %&gt;%
mutate(state = str_remove(iso_3166_2, &quot;AU-&quot;))
ggplot(au_sf) +
geom_sf() +
theme_minimal() </code></pre>
<p><img src="./post/2020-07-20-tt-australian-pets/index_files/figure-html/unnamed-chunk-2-1.png" width="384" /></p>
<div id="get-colors" class="section level4">
<h4>Get colors</h4>
<p>Make a vector of colors for each state/territory.</p>
<pre class="r"><code>state_colors &lt;- au_sf %&gt;%
filter(state %in% colnames(animal_outcomes) &amp;
!is.na(abbrev)) %&gt;%
as.data.frame() %&gt;%
transmute(name = name,
state = state,
color = wesanderson::wes_palette(&quot;BottleRocket2&quot;,
n = 12, type = &#39;c&#39;)[c(1:6,9,12)] %&gt;%
colorspace::lighten(amount = .2),
name_md = glue::glue(&quot;&lt;b style=&#39;color:{color}&#39;&gt;{name}&lt;/b&gt;&quot;)
) </code></pre>
</div>
</div>
<div id="combine-map-and-data" class="section level2">
<h2>Combine Map and Data</h2>
<p>Because the states / territories need to go into the rows (<code>sf</code> has 1 row per geometry), we will be pivoting the data longer before we join.</p>
<pre class="r"><code>animal_outcomes_long &lt;- animal_outcomes %&gt;%
select(-Total) %&gt;%
pivot_longer(cols = 4:11,
names_to = &#39;state&#39;,
values_to = &#39;count&#39;) %&gt;%
pivot_wider(names_from = outcome,
values_from = count) %&gt;%
mutate_all(replace_na, 0) %&gt;%
inner_join(state_colors, by = &#39;state&#39;)</code></pre>
</div>
<div id="combine-rehomed-and-released" class="section level2">
<h2>Combine Rehomed and Released</h2>
<p>Wild animals are obviously released — rather than rehomed — but both can be viewed as the alternative to being euthanized, so we will combine them. Really not sure what “Other” would mean, so let’s just exclude it.</p>
<pre class="r"><code>animal_outcomes_long &lt;- animal_outcomes_long %&gt;%
mutate(`Not Euthanized` = (Reclaimed + Rehomed + Released),
ratio = (`Not Euthanized` + 1) / (Euthanized + 1)
)
animal_outcomes_long[1:5,1:8]</code></pre>
<pre><code>## # A tibble: 5 x 8
## year animal_type state Reclaimed Rehomed Other Euthanized Released
## &lt;dbl&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
## 1 1999 Dogs ACT 610 1245 12 360 0
## 2 1999 Dogs NSW 3140 7525 745 9221 0
## 3 1999 Dogs NT 205 526 955 9 0
## 4 1999 Dogs QLD 1392 5489 860 9214 0
## 5 1999 Dogs SA 2329 1105 380 1701 0</code></pre>
<pre class="r"><code>heatmap_plot &lt;- animal_outcomes_long %&gt;%
ggplot(aes(x = year, y = name_md, fill = ratio)) +
geom_tile() +
scale_fill_fermenter(palette = &#39;Spectral&#39;,
limits = c(1/16, 16),
breaks = c(1/16, 1/8, 1/4, 1/2, 1, 2, 4, 8, 16),
trans = &#39;log2&#39;,
direction = 8,
show.limits = F,
labels = c(&#39;More\nEuthanizations&#39;,
&#39;8 x&#39;, &#39;4 x&#39;, &#39;2 x&#39;, &#39;1 x&#39;, &#39;2 x&#39;, &#39;4 x&#39;, &#39;8 x&#39;,
&#39;More\nRehomes &amp; Releases&#39;),
guide = guide_colorsteps(title = NULL)
) +
scale_x_continuous(expand = c(0,0)) +
facet_wrap(~animal_type, ncol = 3) +
labs(title = &quot;Breakdown by Animal Type&quot;) +
theme_bw(base_size = 16) +
theme(
plot.title = element_text(hjust = 0.5),
plot.margin = margin(t = 25, b = 0),
legend.box.margin = margin(),
legend.margin = margin(b = -10),
legend.position = &#39;top&#39;,
axis.text.y.left = element_markdown(size = 12),
panel.border = element_blank(),
line = element_blank(),
axis.title = element_blank(),
axis.ticks.length = unit(0, &#39;pt&#39;),
legend.key.width = unit(100, &#39;pt&#39;),
legend.key.height = unit(10, &#39;pt&#39;),
strip.background = element_rect(color = NA,
fill = &#39;grey95&#39;)
)
heatmap_plot</code></pre>
<p><img src="./post/2020-07-20-tt-australian-pets/index_files/figure-html/unnamed-chunk-6-1.png" width="672" /></p>
<pre class="r"><code>au_map &lt;- au_sf %&gt;%
filter(state %in% colnames(animal_outcomes) &amp;
!is.na(abbrev)) %&gt;%
ggplot(aes(fill = name)) +
geom_sf(color= &#39;grey40&#39;, size =1/8) +
scale_fill_manual(values = state_colors %&gt;% select(name, color) %&gt;% deframe(),
guide = guide_none()) +
theme_void() +
theme(legend.position = &#39;none&#39;,
legend.key = element_blank(),
plot.margin = margin()
)
au_map</code></pre>
<p><img src="./post/2020-07-20-tt-australian-pets/index_files/figure-html/unnamed-chunk-7-1.png" width="672" /></p>
<pre class="r"><code>line_plot &lt;- animal_outcomes_long %&gt;%
group_by(name, year, name_md) %&gt;%
summarize(&#39;Not Euthanized&#39; = sum(`Not Euthanized`),
Euthanized = sum(Euthanized),
ratio = (`Not Euthanized` + 1) / (Euthanized + 1),
.groups = &#39;keep&#39;) %&gt;%
ggplot(aes(x = year, y = ratio, color = name_md)) +
geom_hline(yintercept = 1, color = &#39;grey35&#39;, size = 1) +
geom_smooth(alpha = 0, size = 1.75) +
scale_color_manual(values = state_colors %&gt;% select(name_md, color) %&gt;% deframe() %&gt;%
alpha(0.85),
name = &#39;State or Territory&#39;) +
scale_y_continuous(limits = c(1/2, 16),
breaks = c(1/2, 1, 2, 4, 8, 16),
trans = &#39;log2&#39;,
labels = c(&#39;More\nEuthanizations&#39;,
&#39;1 x&#39;, &#39;2 x&#39;, &#39;4 x&#39;, &#39;8 x&#39;,
&#39;More\nRehomes&#39;), position = &#39;right&#39;) +
labs(title = &#39;Total&#39;) +
theme_bw(base_size = 14) +
theme(
plot.title.position = &#39;panel&#39;,
plot.margin = margin(),
aspect.ratio = 1,
panel.grid.major = element_line(size = 0.35, color = &#39;grey70&#39;),
panel.border = element_blank(),
legend.text = element_markdown(),
legend.key = element_blank(),
axis.title = element_blank(),
axis.ticks.length = unit(0, &#39;pt&#39;),
legend.key.width = unit(0, &#39;pt&#39;),
legend.key.height = unit(0, &#39;pt&#39;),
legend.position = &#39;left&#39;
)
line_plot</code></pre>
<pre><code>## `geom_smooth()` using method = &#39;loess&#39; and formula &#39;y ~ x&#39;</code></pre>
<pre><code>## Warning: Removed 3 rows containing non-finite values (stat_smooth).</code></pre>
<p><img src="./post/2020-07-20-tt-australian-pets/index_files/figure-html/unnamed-chunk-8-1.png" width="672" /></p>
<pre class="r"><code>showtext_auto()
design &lt;- &quot;
AABBBB
AABBBB
CDDDDD
CDDDDD
CDDDDD
&quot;
final_plot &lt;- au_map + line_plot + plot_spacer() + heatmap_plot +
plot_layout(design = design ) +
plot_annotation(title = &#39;Animal Rehomes &amp; Releases in Australia&#39;,
caption = &#39;A #tidytuesday adventure\nDesign by @TannerKoomar\nData from RSPCA&#39;,
subtitle = &#39;1999 - 2015&#39;,
theme = theme(title = element_text(size = 27,
color = &#39;grey40&#39;,
family = &#39;Josefin Sans&#39;),
plot.subtitle = element_text(size = 20),
plot.caption = element_text(size = 10),
text = element_text(size = 10)
)
) +
theme(axis.text= element_text(size = 8)) &amp;
theme(text = element_text(color = &#39;grey40&#39;, family = &#39;Josefin Sans&#39;),
strip.text = element_text(color = &#39;grey40&#39;, family = &#39;Josefin Sans&#39;),
legend.title = element_text(color = &#39;grey40&#39;, family = &#39;Josefin Sans&#39;)
)
final_plot</code></pre>
<pre><code>## `geom_smooth()` using method = &#39;loess&#39; and formula &#39;y ~ x&#39;</code></pre>
<pre><code>## Warning: Removed 3 rows containing non-finite values (stat_smooth).</code></pre>
<p><img src="./post/2020-07-20-tt-australian-pets/index_files/figure-html/unnamed-chunk-9-1.png" width="960" /></p>
</div>
</description>
</item>
<item>
<title>VCFdbR: A method for expressing biobank-scale Variant Call Format data in a SQLite database using R</title>
<link>/publication/2020-vcfdbr/</link>
<pubDate>Thu, 04 Jun 2020 00:00:00 +0000</pubDate>
<guid>/publication/2020-vcfdbr/</guid>
<description></description>
</item>
<item>
<title>Simple Iteration over Variables with `lm()`</title>
<link>/post/2020-05-02-tutorial-iterate-lm/</link>
<pubDate>Sat, 02 May 2020 00:00:00 +0000</pubDate>
<guid>/post/2020-05-02-tutorial-iterate-lm/</guid>
<description><p>Note that this is not without shortcomings and lacks some flexibility, but it does keep you from having dig deep into how formulas actually work in R – which many (myself included) find confusing in the extreme.</p>
<p>For this example, let’s work with the standard <code>mtcars</code> dataset.</p>
<pre class="r"><code>head(mtcars)</code></pre>
<pre><code>## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1</code></pre>
<div id="the-function-lm_caller" class="section level2">
<h2>The function, <code>lm_caller()</code></h2>
<p>The function we will make – <code>lm_caller()</code> – is rather dull at its core. It just takes in different arguments for the left-hand side (LHS), right-hand side (RHS) and data of an model you want to fit.</p>
<pre class="r"><code>lm_caller &lt;- function(LHS, RHS, data){
formula &lt;- as.formula(paste0(LHS, &quot; ~ &quot;, RHS))
output &lt;- lm(formula, data = data)
return(output)
}</code></pre>
</div>
<div id="run-the-function-manually" class="section level2">
<h2>Run the function manually</h2>
<pre class="r"><code>model_1 &lt;- lm_caller(LHS = &quot;mpg&quot;, RHS = &quot;disp + wt&quot;, data = mtcars)
summary(model_1)</code></pre>
<pre><code>##
## Call:
## lm(formula = formula, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.4087 -2.3243 -0.7683 1.7721 6.3484
##
## Coefficients:
## Estimate Std. Error t value Pr(&gt;|t|)
## (Intercept) 34.96055 2.16454 16.151 4.91e-16 ***
## disp -0.01773 0.00919 -1.929 0.06362 .
## wt -3.35082 1.16413 -2.878 0.00743 **
## ---
## Signif. codes: 0 &#39;***&#39; 0.001 &#39;**&#39; 0.01 &#39;*&#39; 0.05 &#39;.&#39; 0.1 &#39; &#39; 1
##
## Residual standard error: 2.917 on 29 degrees of freedom
## Multiple R-squared: 0.7809, Adjusted R-squared: 0.7658
## F-statistic: 51.69 on 2 and 29 DF, p-value: 2.744e-10</code></pre>
</div>
<div id="iterate-apply-over-many-dependent-and-independent-variables" class="section level2">
<h2>Iterate (apply) over many dependent and independent variables</h2>
<div id="first-make-a-big-ol-list-of-the-different-combinations-of-variables-you-want-in-your-models" class="section level4">
<h4>First, make a big ol’ list of the different combinations of variables you want in your models:</h4>
<pre class="r"><code>left_hand_side &lt;- data.frame(lhs = c(&#39;mpg&#39;, &#39;hp&#39;, &#39;am&#39;))
right_hand_side &lt;- data.frame(rhs = c(&#39;cyl&#39;, &#39;disp&#39;, &#39;wt&#39;, &#39;qsec&#39;, &#39;disp + wt&#39;, &#39;cyl - 1&#39;))</code></pre>
</div>
<div id="now-do-a-nested-apply-over-each-of-those" class="section level4">
<h4>Now do a nested <code>apply()</code> over each of those</h4>
<pre class="r"><code>model_list &lt;- apply(left_hand_side, 1, function(lhs){
apply(right_hand_side, 1,function(rhs){
lm_caller(LHS = lhs, RHS = rhs, data = mtcars)
})
})</code></pre>
<p>One major downside to munging strings for model specification is that the formula stored in the resulting models will all look identical:</p>
<pre class="r"><code>model_list[[1]][1:2]</code></pre>
<pre><code>## [[1]]
##
## Call:
## lm(formula = formula, data = data)
##
## Coefficients:
## (Intercept) cyl
## 37.885 -2.876
##
##
## [[2]]
##
## Call:
## lm(formula = formula, data = data)
##
## Coefficients:
## (Intercept) disp
## 29.59985 -0.04122</code></pre>
<p>Mapping these models back to their original data is a bit of a pain. There is a way to do it that <em>I</em> find much cleaner, so long as you are willing to. . .</p>
</div>
<div id="do-it-tidy" class="section level3">
<h3>Do it tidy!</h3>
<p>If this approach make sense to you, I would recommend <a href="https://towardsdatascience.com/functional-programming-in-r-with-purrr-469e597d0229">this basic tutorial on functional programming with <code>purrr</code> in R</a> and <a href="https://r4ds.had.co.nz/many-models.html">this book chapter on building many models, utilizing the power of the tidyverse</a></p>
<p>First, make a data frame of all the left- and right-hand sides, so we can keep track of them:</p>
<pre class="r"><code>formulae_dat &lt;- tidyr::crossing(left_hand_side, right_hand_side)
head(formulae_dat)</code></pre>
<pre><code>## # A tibble: 6 x 2
## lhs rhs
## &lt;fct&gt; &lt;fct&gt;
## 1 am cyl
## 2 am cyl - 1
## 3 am disp
## 4 am disp + wt
## 5 am qsec
## 6 am wt</code></pre>
<p>Now, <em>add</em> the models to this, with the help of <code>mutate()</code> and <code>map2</code></p>
<p><em>Note</em> we could also change up the dataset as part of this (not sure why you’d want to), but that would require using <code>pmap()</code> instead of <code>map2</code></p>
<pre class="r"><code>model_dat &lt;- dplyr::mutate(formulae_dat,
model = purrr::map2(lhs, rhs, function(lhs, rhs){
lm_caller(LHS = lhs, RHS = rhs, data = mtcars)
})
)</code></pre>
<pre class="r"><code>head(model_dat)</code></pre>
<pre><code>## # A tibble: 6 x 3
## lhs rhs model
## &lt;fct&gt; &lt;fct&gt; &lt;list&gt;
## 1 am cyl &lt;lm&gt;
## 2 am cyl - 1 &lt;lm&gt;
## 3 am disp &lt;lm&gt;
## 4 am disp + wt &lt;lm&gt;
## 5 am qsec &lt;lm&gt;
## 6 am wt &lt;lm&gt;</code></pre>
<p>Having models inside of a dataframe might not seem any more helpful, but you can write a function to extract the parts that you really want. Or, rely on <code>broom</code> for more common models.</p>
<p><em>Note</em> here I’m using lambda style function specification, rather than the more verbose <code>function(x){}</code> format.</p>
<pre class="r"><code>model_dat &lt;- dplyr::mutate(model_dat,
model_summary = purrr::map(model, ~broom::glance(.x)),
model_coefficient = purrr::map(model, ~broom::tidy(.x))
)
head(model_dat)</code></pre>
<pre><code>## # A tibble: 6 x 5
## lhs rhs model model_summary model_coefficient
## &lt;fct&gt; &lt;fct&gt; &lt;list&gt; &lt;list&gt; &lt;list&gt;
## 1 am cyl &lt;lm&gt; &lt;tibble [1 × 11]&gt; &lt;tibble [2 × 5]&gt;
## 2 am cyl - 1 &lt;lm&gt; &lt;tibble [1 × 11]&gt; &lt;tibble [1 × 5]&gt;
## 3 am disp &lt;lm&gt; &lt;tibble [1 × 11]&gt; &lt;tibble [2 × 5]&gt;
## 4 am disp + wt &lt;lm&gt; &lt;tibble [1 × 11]&gt; &lt;tibble [3 × 5]&gt;
## 5 am qsec &lt;lm&gt; &lt;tibble [1 × 11]&gt; &lt;tibble [2 × 5]&gt;
## 6 am wt &lt;lm&gt; &lt;tibble [1 × 11]&gt; &lt;tibble [2 × 5]&gt;</code></pre>
<p>Now, with an <code>unnest</code>, we can access the most relevant parts of each model.</p>
<pre class="r"><code>tidyr::unnest(model_dat[,c(-3,-5)], model_summary)</code></pre>
<pre><code>## # A tibble: 18 x 13
## lhs rhs r.squared adj.r.squared sigma statistic p.value df logLik
## &lt;fct&gt; &lt;fct&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt;
## 1 am cyl 0.273 0.249 0.432 11.3 2.15e- 3 2 -17.5
## 2 am cyl … 0.253 0.229 0.560 10.5 2.84e- 3 1 -26.3
## 3 am disp 0.350 0.328 0.409 16.1 3.66e- 4 2 -15.8
## 4 am disp… 0.482 0.446 0.371 13.5 7.17e- 5 3 -12.1
## 5 am qsec 0.0528 0.0213 0.494 1.67 2.06e- 1 2 -21.8
## 6 am wt 0.480 0.462 0.366 27.6 1.13e- 5 2 -12.2
## 7 hp cyl 0.693 0.683 38.6 67.7 3.48e- 9 2 -161.
## 8 hp cyl … 0.939 0.937 40.5 476. 2.23e-20 1 -163.
## 9 hp disp 0.626 0.613 42.6 50.1 7.14e- 8 2 -164.
## 10 hp disp… 0.635 0.609 42.9 25.2 4.57e- 7 3 -164.
## 11 hp qsec 0.502 0.485 49.2 30.2 5.77e- 6 2 -169.
## 12 hp wt 0.434 0.415 52.4 23.0 4.15e- 5 2 -171.
## 13 mpg cyl 0.726 0.717 3.21 79.6 6.11e-10 2 -81.7
## 14 mpg cyl … 0.734 0.725 11.0 85.5 2.02e-10 1 -122.
## 15 mpg disp 0.718 0.709 3.25 76.5 9.38e-10 2 -82.1
## 16 mpg disp… 0.781 0.766 2.92 51.7 2.74e-10 3 -78.1
## 17 mpg qsec 0.175 0.148 5.56 6.38 1.71e- 2 2 -99.3
## 18 mpg wt 0.753 0.745 3.05 91.4 1.29e-10 2 -80.0
## # … with 4 more variables: AIC &lt;dbl&gt;, BIC &lt;dbl&gt;, deviance &lt;dbl&gt;,
## # df.residual &lt;int&gt;</code></pre>
<pre class="r"><code>tidyr::unnest(model_dat[,-3:-4], model_coefficient)</code></pre>
<pre><code>## # A tibble: 36 x 7
## lhs rhs term estimate std.error statistic p.value
## &lt;fct&gt; &lt;fct&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
## 1 am cyl (Intercept) 1.31 0.280 4.68 0.0000571
## 2 am cyl cyl -0.146 0.0435 -3.36 0.00215
## 3 am cyl - 1 cyl 0.0498 0.0154 3.24 0.00284
## 4 am disp (Intercept) 0.955 0.155 6.18 0.000000855
## 5 am disp disp -0.00238 0.000593 -4.02 0.000366
## 6 am disp + wt (Intercept) 1.60 0.276 5.81 0.00000266
## 7 am disp + wt disp 0.000451 0.00117 0.386 0.703
## 8 am disp + wt wt -0.404 0.148 -2.73 0.0108
## 9 am qsec (Intercept) 1.55 0.890 1.74 0.0914
## 10 am qsec qsec -0.0642 0.0496 -1.29 0.206
## # … with 26 more rows</code></pre>
<p>Functions like <code>filter()</code> and <code>ggplot()</code> are extremely useful at this point to get a beter feel for what your mnodels are actually saying, but we will save that for another time.</p>
</div>
</div>
<div id="plot-from-multiple-models-with-ggplot" class="section level2">
<h2>Plot from multiple models with ggplot</h2>
<pre class="r"><code>library(tidyverse, quietly = T)</code></pre>
<pre><code>## ── Attaching packages ───────────────────────────────────────────────────────────────────────────────── tidyverse 1.3.0 ──</code></pre>
<pre><code>## ✓ ggplot2 3.3.0 ✓ purrr 0.3.3
## ✓ tibble 3.0.0 ✓ dplyr 1.0.0
## ✓ tidyr 1.0.2 ✓ stringr 1.4.0
## ✓ readr 1.3.1 ✓ forcats 0.5.0</code></pre>
<pre><code>## ── Conflicts ──────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()</code></pre>
<pre class="r"><code>model_dat %&gt;%
unnest(model_coefficient) %&gt;%
mutate(
low = estimate - std.error,
high = estimate + std.error,
formula = paste(lhs, &quot;~&quot;, rhs)
) %&gt;%
ggplot(aes(estimate, term, xmin = low, xmax = high, height = 0)) +
geom_vline(xintercept = 0, color = &#39;grey50&#39;) +
geom_errorbarh() +
geom_point() +
geom_text(aes(label = round(p.value, 3)), nudge_y = 0.33, ) +
facet_wrap(vars(formula), scales = &#39;free&#39;, ncol = 2) </code></pre>
<p><img src="./post/2020-05-02-tutorial-iterate-lm/index_files/figure-html/unnamed-chunk-11-1.png" width="672" /></p>
<pre class="r"><code>model_dat %&gt;%
unnest(model_coefficient) %&gt;%
filter(str_detect(rhs, &quot;cyl&quot;)) %&gt;%
mutate(
low = estimate - std.error,
high = estimate + std.error
) %&gt;%
ggplot(aes(estimate, term, xmin = low, xmax = high, height = 0)) +
geom_vline(xintercept = 0, color = &#39;grey50&#39;) +
geom_errorbarh() +
geom_point() +
geom_text(aes(label = round(p.value, 3)), nudge_y = 0.33, ) +
facet_grid(rows = vars(lhs), cols = vars(rhs), scales = &#39;free&#39;) </code></pre>
<p><img src="./post/2020-05-02-tutorial-iterate-lm/index_files/figure-html/unnamed-chunk-12-1.png" width="480" /></p>
<p>Plotting the “acutal” vs “predicted” (fitted) values takes a bit of work with <code>pivot_longer()</code>, and is probably best done separately for each outcome variable.</p>
<p>Remember that ggplots are actually objects, so we can actually stick them into a dataframe and then plot them later!</p>
<pre class="r"><code>plot_dat &lt;- model_dat %&gt;%
mutate(model_resid = map(model, broom::augment)) %&gt;%
select(lhs, rhs, model_resid) %&gt;%
unnest(model_resid) %&gt;%
pivot_longer(cols = c(-starts_with(&quot;.&quot;), -lhs, -rhs),
names_to = &#39;name&#39;,
values_to =&#39;actual&#39;
) %&gt;%
filter(lhs == name) %&gt;%
nest(data = -lhs) %&gt;%
mutate(plot = map2(data, lhs, ~(
ggplot(.x, aes(x = actual, y = .fitted, height = 0)) +
geom_point() +
facet_wrap(~rhs, scales = &#39;free&#39;) +
labs(title = .y)
)))
plot_dat</code></pre>
<pre><code>## # A tibble: 3 x 3
## lhs data plot
## &lt;fct&gt; &lt;list&gt; &lt;list&gt;
## 1 am &lt;tibble [192 × 11]&gt; &lt;gg&gt;
## 2 hp &lt;tibble [192 × 11]&gt; &lt;gg&gt;
## 3 mpg &lt;tibble [192 × 11]&gt; &lt;gg&gt;</code></pre>
<pre class="r"><code>plot_dat$plot</code></pre>
<pre><code>## [[1]]</code></pre>
<p><img src="./post/2020-05-02-tutorial-iterate-lm/index_files/figure-html/unnamed-chunk-14-1.png" width="672" /></p>
<pre><code>##
## [[2]]</code></pre>
<p><img src="./post/2020-05-02-tutorial-iterate-lm/index_files/figure-html/unnamed-chunk-14-2.png" width="672" /></p>
<pre><code>##
## [[3]]</code></pre>
<p><img src="./post/2020-05-02-tutorial-iterate-lm/index_files/figure-html/unnamed-chunk-14-3.png" width="672" /></p>
</div>
</description>
</item>
<item>
<title>Tidy Tuesday: NFL Stadium Attendance</title>
<link>/post/2020-02-04-tt-football/</link>
<pubDate>Tue, 04 Feb 2020 00:00:00 +0000</pubDate>
<guid>/post/2020-02-04-tt-football/</guid>
<description><p>Dip into the new <code>ggttext</code> package to get some rich text formatting in a plot&rsquo;s title. Also: sports.</p>
<ul>
<li>
<a href="#load-in-data">Load in data</a>
</li>
<li>
<a href="#the-question-to-super-bowl-winners-have-harder-schedules">The question: to super bowl winners have harder schedules?</a>
</li>
<li>
<a href="#summarize-data">Summarize data</a>
</li>
<li>
<a href="#test-the-difference-in-schedule-strength">Test the difference in schedule strength</a>
</li>
<li>
<a href="#plot">Plot</a>
</li>
<li>
<a href="#bonus-color-by-team-name">Bonus: Color by Team Name</a>
</li>
<li>
<a href="#bonus-what-is-the-bump-in-attendance-the-year-after-winning-a-superbowl">Bonus: What is the bump in attendance the year after winning a superbowl?</a>
</li>
</ul>
<h2 id="load-in-data">Load in data</h2>
<pre><code class="language-r">attendance &lt;- read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-02-04/attendance.csv',
col_types = cols())
glimpse(attendance)
</code></pre>
<pre><code>## Observations: 10,846
## Variables: 8
## $ team &lt;chr&gt; &quot;Arizona&quot;, &quot;Arizona&quot;, &quot;Arizona&quot;, &quot;Arizona&quot;, &quot;Arizon…
## $ team_name &lt;chr&gt; &quot;Cardinals&quot;, &quot;Cardinals&quot;, &quot;Cardinals&quot;, &quot;Cardinals&quot;,…
## $ year &lt;dbl&gt; 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 200…
## $ total &lt;dbl&gt; 893926, 893926, 893926, 893926, 893926, 893926, 893…
## $ home &lt;dbl&gt; 387475, 387475, 387475, 387475, 387475, 387475, 387…
## $ away &lt;dbl&gt; 506451, 506451, 506451, 506451, 506451, 506451, 506…
## $ week &lt;dbl&gt; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, …
## $ weekly_attendance &lt;dbl&gt; 77434, 66009, NA, 71801, 66985, 44296, 38293, 62981…
</code></pre>
<pre><code class="language-r">standings &lt;- read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-02-04/standings.csv',
col_types = cols())
glimpse(standings)
</code></pre>
<pre><code>## Observations: 638
## Variables: 15
## $ team &lt;chr&gt; &quot;Miami&quot;, &quot;Indianapolis&quot;, &quot;New York&quot;, &quot;Buffalo&quot;, …
## $ team_name &lt;chr&gt; &quot;Dolphins&quot;, &quot;Colts&quot;, &quot;Jets&quot;, &quot;Bills&quot;, &quot;Patriots&quot;…
## $ year &lt;dbl&gt; 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, …
## $ wins &lt;dbl&gt; 11, 10, 9, 8, 5, 13, 12, 9, 7, 4, 3, 12, 11, 7, …
## $ loss &lt;dbl&gt; 5, 6, 7, 8, 11, 3, 4, 7, 9, 12, 13, 4, 5, 9, 10,…
## $ points_for &lt;dbl&gt; 323, 429, 321, 315, 276, 346, 333, 321, 367, 185…
## $ points_against &lt;dbl&gt; 226, 326, 321, 350, 338, 191, 165, 255, 327, 359…
## $ points_differential &lt;dbl&gt; 97, 103, 0, -35, -62, 155, 168, 66, 40, -174, -2…
## $ margin_of_victory &lt;dbl&gt; 6.1, 6.4, 0.0, -2.2, -3.9, 9.7, 10.5, 4.1, 2.5, …
## $ strength_of_schedule &lt;dbl&gt; 1.0, 1.5, 3.5, 2.2, 1.4, -1.3, -2.5, -0.2, -1.4,…
## $ simple_rating &lt;dbl&gt; 7.1, 7.9, 3.5, 0.0, -2.5, 8.3, 8.0, 3.9, 1.1, -1…
## $ offensive_ranking &lt;dbl&gt; 0.0, 7.1, 1.4, 0.5, -2.7, 1.5, 0.0, 0.6, 3.2, -8…
## $ defensive_ranking &lt;dbl&gt; 7.1, 0.8, 2.2, -0.5, 0.2, 6.8, 8.0, 3.3, -2.1, -…
## $ playoffs &lt;chr&gt; &quot;Playoffs&quot;, &quot;Playoffs&quot;, &quot;No Playoffs&quot;, &quot;No Playo…
## $ sb_winner &lt;chr&gt; &quot;No Superbowl&quot;, &quot;No Superbowl&quot;, &quot;No Superbowl&quot;, …
</code></pre>
<h2 id="the-question-to-super-bowl-winners-have-harder-schedules">The question: to super bowl winners have harder schedules?</h2>
<p>I am curious if teams that win the super bowl have an easier or harder schedule than the other teams that make it to the playoffs. The <code>strength_of_schedule</code> variable provides a simple way to test this.</p>
<p>The only data manipulation we need to do is combine <code>playoffs</code> and <code>sb_winner</code>:</p>
<pre><code class="language-r">standings &lt;- standings %&gt;%
mutate(final_position = if_else(sb_winner == &quot;Won Superbowl&quot;, sb_winner, playoffs))
</code></pre>
<h2 id="summarize-data">Summarize data</h2>
<pre><code class="language-r">standing_summary &lt;- standings %&gt;%
group_by(final_position) %&gt;%
summarize(less_zero = sum(strength_of_schedule &lt; 0),
total = n(),
percent_less_zero = less_zero / total,
median_strength = median(strength_of_schedule)
)
standing_summary
</code></pre>
<pre><code>## # A tibble: 3 x 5
## final_position less_zero total percent_less_zero median_strength
## &lt;chr&gt; &lt;int&gt; &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt;
## 1 No Playoffs 170 398 0.427 0.2
## 2 Playoffs 132 220 0.6 -0.5
## 3 Won Superbowl 8 20 0.4 0.2
</code></pre>
<p>It looks like most teams that make it to the playoffs have an easier schedule (60% of them hace an average opponent rating less than zero) than those that win the super bowl (only 40% have average opponent rating less than zero). Teams that don&rsquo;t make the playoffs also seem to have more difficult schedule.</p>
<h2 id="test-the-difference-in-schedule-strength">Test the difference in schedule strength</h2>
<p>The Kruskal-Wallis is suitable for multiple rank-based comparisons of groups:</p>
<pre><code class="language-r">standings %&gt;%
kruskal.test(strength_of_schedule ~ final_position, data = .)
</code></pre>
<pre><code>##
## Kruskal-Wallis rank sum test
##
## data: strength_of_schedule by final_position
## Kruskal-Wallis chi-squared = 27.31, df = 2, p-value = 1.174e-06
</code></pre>
<p>But sometimes, doing pairwise Wilcox tests can be more interpretable.</p>
<pre><code class="language-r">standings %&gt;%
filter(final_position != &quot;Won Superbowl&quot;) %&gt;%
wilcox.test(strength_of_schedule ~ final_position, data = .)
</code></pre>
<pre><code>##
## Wilcoxon rank sum test with continuity correction
##
## data: strength_of_schedule by final_position
## W = 54732, p-value = 2.549e-07
## alternative hypothesis: true location shift is not equal to 0
</code></pre>
<pre><code class="language-r">standings %&gt;%
filter(final_position != &quot;No Playoffs&quot;) %&gt;%
wilcox.test(strength_of_schedule ~ final_position, data = .)
</code></pre>
<pre><code>##
## Wilcoxon rank sum test with continuity correction
##
## data: strength_of_schedule by final_position
## W = 1599, p-value = 0.04333
## alternative hypothesis: true location shift is not equal to 0
</code></pre>
<h2 id="plot">Plot</h2>
<p>Manually specify some colors (taken from the fun <code>wesanderson</code> package)</p>
<pre><code class="language-r">final_position_pal = c(
&quot;No Playoffs&quot; = &quot;#F2AD00&quot;,
&quot;Playoffs&quot; = &quot;#00A08A&quot;,
&quot;Won Superbowl&quot; = &quot;#FF0000&quot;
)
</code></pre>
<p>We will use the features of the great new <code>ggtext</code> package to color text in the subtitle of the plot, obviating the need for a figure legend.</p>
<pre><code class="language-r">library(ggtext)
standings %&gt;%
ggplot(aes(x = final_position, y = strength_of_schedule, fill = final_position)) +
geom_hline(yintercept = 0, lwd = 0.5, lty = 2, color = 'grey 50') +
geom_boxplot() +
#geom_jitter(width = 0.25) +
geom_text(data = standing_summary,
inherit.aes = FALSE,
nudge_y = 0.22,
mapping = aes(x = final_position, y = median_strength, label = median_strength)) +
scale_fill_manual(values = final_position_pal,
guide = 'none'
) +
theme_minimal() +
theme(axis.title = element_blank(),
axis.text.x = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank(),
plot.title = element_textbox(),
plot.subtitle = element_markdown(linewidth = 20)
) +
labs(title = &quot;**No Easy Road to Super Bowl Victory**&quot;,
subtitle = &quot;Since 2000, NFL &lt;b style='color:#F2AD00'&gt;teams that miss the playoffs&lt;/b&gt; have a harder schedule (an average opponent
rating greater than the dashed line at zero) than &lt;b style='color:#00A08A'&gt;teams that make it to the playoffs&lt;/b&gt;.
A &lt;b style='color:#FF0000'&gt;Super Bowl winner's&lt;/b&gt; schedule is much tougher by comparison.&quot;
) +
ggsave(filename = 'featured.png', width = 7, height = 7)
</code></pre>
<p><img src="2020-02-04-tt-football_files/figure-markdown_github/unnamed-chunk-6-1.png" alt=""></p>
<h2 id="bonus-color-by-team-name">Bonus: Color by Team Name</h2>
<p>How does it look to plot individual points for each team, coloring them accoring to their team colors (thanks to the <code>teamcolors</code> package)?</p>
<pre><code class="language-r">team_fill = teamcolors::league_pal('nfl', which = 2)
team_color = teamcolors::league_pal('nfl', which = 1)
## Use just team name, not the home city (which changes for a couple teams)
names(team_fill) &lt;- str_remove(names(team_fill), &quot;^.* &quot;)
names(team_color) &lt;- str_remove(names(team_color), &quot;^.* &quot;)
standings %&gt;%
ggplot(aes(x = final_position, y = strength_of_schedule, fill = team_name, color = team_name)) +
geom_jitter(width = 0.4, pch = 23, size = 3) +
scale_fill_manual(values = team_fill,
guide = 'none'
) +
scale_color_manual(values = team_color,
guide = 'none'
) +
theme_minimal() +
theme(axis.title = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank(),
plot.title = element_textbox(),
plot.subtitle = element_markdown(linewidth = 20)
)
</code></pre>
<p><img src="2020-02-04-tt-football_files/figure-markdown_github/unnamed-chunk-7-1.png" alt=""></p>
<p>Ugly. Too many of the teams have colors that are close to one another.</p>
<h2 id="bonus-what-is-the-bump-in-attendance-the-year-after-winning-a-superbowl">Bonus: What is the bump in attendance the year after winning a superbowl?</h2>
<p>Making use of the <code>lag()</code> function, if you account for the fact that each team has a different &ldquo;baseline&rdquo; of attendance, it looks like the year after a superbowl win, attendence to away games may go up a bit. Home games and total attendance doesn&rsquo;t really change though.</p>
<pre><code class="language-r">attendance %&gt;%
select(team, team_name, year, total, home, away) %&gt;%
distinct() %&gt;%
group_by(team) %&gt;%
## adjust attendance on a per-team basis to account for a difference baseline for each team
mutate_at(vars(total, home, away), .funs = ~scale(., scale = FALSE) ) %&gt;%
ungroup() %&gt;%
full_join(standings) %&gt;%
group_by(team) %&gt;%
mutate_all(.funs = list(last_year = ~lag(.))) %&gt;%
filter(sb_winner_last_year == &quot;Won Superbowl&quot;) %&gt;%
filter(!is.na(sb_winner_last_year)) %&gt;%
ungroup() %&gt;%
arrange(team, year) %&gt;%
gather(attendance_the_year_after_winning_superbowl, value, total, total_last_year, home, home_last_year, away, away_last_year) %&gt;%
ggplot(aes(x = attendance_the_year_after_winning_superbowl, y = value)) +
geom_boxplot() +
ggpubr::stat_compare_means() +
theme_minimal()
</code></pre>
<pre><code>## Joining, by = c(&quot;team&quot;, &quot;team_name&quot;, &quot;year&quot;)
## `mutate_all()` ignored the following grouping variables:
## Column `team`
## Use `mutate_at(df, vars(-group_cols()), myoperation)` to silence the message.
</code></pre>
<p><img src="2020-02-04-tt-football_files/figure-markdown_github/unnamed-chunk-8-1.png" alt=""></p></description>
</item>
<item>
<title>Genetic Intersections of Language and Neuropsychiatric Conditions</title>
<link>/publication/2020-language-review-paper/</link>
<pubDate>Fri, 17 Jan 2020 00:00:00 +0000</pubDate>
<guid>/publication/2020-language-review-paper/</guid>
<description></description>
</item>
<item>
<title>Ensemble Modeling of Neurocognitive Performance Using MRI-Derived Brain Structure Volumes</title>
<link>/publication/2019-miccai-paper/</link>
<pubDate>Thu, 10 Oct 2019 00:00:00 +0000</pubDate>
<guid>/publication/2019-miccai-paper/</guid>
<description></description>
</item>
<item>
<title>Tidy Tuesday: University Research Funding</title>
<link>/post/2019-05-08-tt-uni-funding/</link>
<pubDate>Wed, 08 May 2019 00:00:00 +0000</pubDate>