-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides.Rmd
2002 lines (1663 loc) · 50.5 KB
/
slides.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "How to Create Publication-Ready Tables in R"
subtitle: "UseR! 2022"
author: "Raymond Balise with Anna Calderon, Francisco Cardozo, Lauren Nahodyl"
date: "`r format(Sys.time(), '%b %d, %Y')`"
output:
xaringan::moon_reader:
css: ["default", "assets/sydney.css", "assets/cssninja-scaffold.css", "assets/ninjutsu.css"]
lib_dir: libs
nature:
highlightLines: true
highlightSpans: false
countIncrementalSlides: false
beforeInit: "assets/macros.js"
ratio: '16:9' # alternatives '16:9' or '4:3' or others e.g. 13:9
navigation:
scroll: false # disable slide transitions by scrolling
editor_options:
chunk_output_type: console
---
```{r setup, echo = FALSE}
knitr::opts_chunk$set(include = TRUE)
knitr::opts_chunk$set(comment = NA)
xaringanExtra::use_tile_view()
```
```{r jquery, echo=FALSE}
# This is to deal with issues when making slides.
# See: https://github.com/jhelvy/xaringanBuilder/issues/46
htmltools::tagList(rmarkdown::html_dependency_jquery())
```
```{r slides, eval=FALSE, echo=FALSE}
# make pdf of slides
xaringanBuilder::build_pdf("./slides.Rmd")
```
```{r packages, echo=FALSE}
# Helper packages - need dplyr and ggplot
library(conflicted)
conflict_prefer("select", "dplyr", quiet = TRUE)
conflict_prefer("filter", "dplyr", quiet = TRUE)
library(dplyr)
library(tidyr)
library(knitr)
conflict_prefer("continuous_summary", "gtsummary", quiet = TRUE)
conflict_prefer("as_flextable", "gtsummary", quiet = TRUE)
conflict_prefer("void", "reactablefmtr", quiet = TRUE)
```
# Who are we?
+ Francisco - A Ph.D. student at The University of Miami's Miller School of Medicine, quantifying policies to prevent/delay childhood alcohol use.
The rest of us work at UM:
+ Ray - An Associate Professor of biostatistics (really a data scientist) studying the intersection of HIV, mental health and drug addiction.
+ Lauren - A statistician/data scientist at UM's Sylvester Comprehensive Cancer Center
+ Anna - A data scientist working with Ray on HIV, mental health and addiction
---
# Disclosures
We have no financial disclosures to report.
# License
.small[
This work is licensed under a [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/).
]
---
# General Comments
.small[
+ I use and teach with .blue[`tidyverse`] and .blue[`tidymodels`]. Because not everybody has been able to upgrade to R 4.2, we left .blue[`%>%`] pipes in this presentation but we strongly suggest that people upgrade and use the most excellent .blue[`|>`] pipe.
+ The slides are done with the .blue[`xaringan`] package. There is bug somewhere that causes the slides to render quickly but then there is a delay (about a minute) before the details are shown on two of my Macs. Sorry! If you have the same issue add a comment:
+ https://community.rstudio.com/t/rstudio-miserably-slow-on-os-monterey-when-knitting-xaringan-slides/140183
]
---
## Where did the idea for this talk come from? $_1$
.center[
![:scale 90%](./images/reproducible.jpg)
https://vimeo.com/585821837
]
---
## Where did the idea for this talk come from? $_2$
+ When I used to primarily work in SAS, I would get my tables close to correct with *proc whatever* and then export to HTML, tweak things in Excel, and wait for the call saying:
> We are really sorry but there is "this guy"...
+ Of course, every number in the paper, including the tables, would change and I would mutter about needing to learn R.
+ I learned R Markdown and finally stopped crying whenever my phone would ring.
---
# When I was in school...
+ Journal tables (and figures) were monochrome and simple.
+ Now we have tables that are artfully formatted and have art that is ready for Twitter.
+ The distinction between tables and figures has completely blurred.
.pull-left[
.center[![:scale 100%](images/NEJM1.jpg)]
]
.pull-right[
.center[![:scale 90%](images/NEJM2.jpg)]
]
---
# When should you use a table?
+ Tables are useful to show the exact values of your data or estimates.
+ They are not the best solution to show a lot of data or if you want to show the data in a compact space.
+ They are not usually intended to give a quick, visual representation of data.
+ However, the core psychological principles leading to fast and accurate judgment in graphics apply to both charts and tables.
+ Read/Study/Live *Visualizing Data* and *The Elements of Graphing Data* by William S. Cleveland.
---
class: segue
# Best Practices in Plots (And Graphics)
---
# Tufte on Visualizations
.small[
+ One of the visualization thought leaders in the 1980s, Edward Tufte, stressed the importance of erasing all unnecessary ink from the page. The same holds true for tables.
+ When in doubt, erase.
.center[![:scale 50%](images/ink_to_information.jpg)]
]
.tiny[https://playfairdata.com/data-ink-ratio-animation-and-how-to-apply-it-in-tableau/]
---
# Gestalt Principles
.pull-left[
Gestalt Law of Proximity - Things close together are automatically grouped.]
.center[
![:scale 10%](images/proximity.jpg)
]
.pull-left[Gestalt Law of Similarity - Things of the same color will be grouped. If one thing is a different color, it will pop off of the page.]
.center[
![:scale 15%](images/similarity.jpg)
]
.pull-left[
Gestalt Law of Closure - You can draw part of a bounding box and the brain will fill in the rest.]
.center[
<br>
![:scale 10%](images/closure.jpg)
]
.tiny[https://blog.xlcubed.com/2008/05/gestalt-laws-charts-and-tables-the-way-your-brain-wants-them-to-be/]
---
# Schwabish's Rules for Better Tables
.center[
.pull-left[
![:scale 100%](images/costbenefit.jpg)
https://doi.org/10.1017/bca.2020.11
]
.pull-right[![:scale 60%](images/better.jpg)
https://cup.columbia.edu/book/better-data-visualizations/9780231193115
]]
---
### Schwabish's Ten Rules for Better Tables + Balise Three
.small[
1. Offset the .red[Heads] from the Body
2. Use .red[Subtle Dividers] Rather Than Heavy Gridlines
3. .red[Right-Align Numbers] and Heads
4. .red[Left-Align Text] and Heads
5. Select the Appropriate Level of .red[Precision]
6. Guide Your Reader with .red[Space] between Rows and Columns
7. .red[Remove] Unit .red[Repetition]
8. Highlight .red[Outliers]
9. .red[Group Similar] Data and Increase White Space
10. Add .red[Visualizations] When Appropriate
11. Draw Attention to the .red[Key Point(s)]
12. Use .red[Annotations] to Explain the Statistics
13. Make .red[Captions/Titles] Self-Contained
+ Explain Sample Size, Who and When
]
.tiny[Schwabish, Jonathan A., Journal of Benefit-Cost Analysis; Berlin Vol. 11, Iss. 2, (Summer 2020): 151-178. DOI:10.1017/bca.2020.11]
---
# What is the Key Take-Away Point in These Data?
.pull-left[
![:scale 100%](images/ariana_before.jpg)
]
--
.pull-left[.center[
![:scale 70%](images/ariana_after.jpg)
]]
---
# Critique PReP Table 1 - Excel Default
.pull-left[
![:scale 100%](images/ariana_before.jpg)
]
.pull-right[.small[
1. .red[Heads] `r emo::ji("check")`
2. .red[Subtle Dividers] `r emo::ji("x")`
3. .red[Right-Align Numbers] `r emo::ji("x")`
4. .red[Left-Align Text] `r emo::ji("x")`
5. .red[Precision] `r emo::ji("check")`
6. .red[Space] `r emo::ji("check")`
7. .red[Remove Repetition] `r emo::ji("x")`
8. .red[Outliers]
9. .red[Group Similar] `r emo::ji("check")`
10. .red[Visualizations]
11. .red[Key Point(s)] `r emo::ji("x")`
12. .red[Annotations]
13. .red[Caption/Title] `r emo::ji("x")`
]]
---
# Critique PReP Table 1 - Also Excel
.pull-left[
![:scale 80%](images/ariana_after.jpg)
]
.pull-right[.small[
1. .red[Heads] `r emo::ji("check")`
2. .red[Subtle Dividers] `r emo::ji("check")`
3. .red[Right-Align Numbers] `r emo::ji("x")`
4. .red[Left-Align Text] `r emo::ji("check")`
5. .red[Precision] `r emo::ji("check")`
6. .red[Space] `r emo::ji("check")`
7. .red[Remove Repetition] `r emo::ji("x")`
8. .red[Outliers]
9. .red[Group Similar] `r emo::ji("check")`
10. .red[Visualizations]
11. .red[Key Point(s)] `r emo::ji("check")`
12. .red[Annotations]
13. .red[Caption/Title] `r emo::ji("check")`
]]
---
# Critique PReP Table 1 - (Version 1.1)
.pull-left[
![:scale 80%](images/ariana_after_1.jpg)
]
.pull-right[.small[
1. .red[Heads] `r emo::ji("check")`
2. .red[Subtle Dividers] `r emo::ji("check")`
3. .red[Right-Align Numbers] `r emo::ji("x")`
4. .red[Left-Align Text] `r emo::ji("check")`
5. .red[Precision] `r emo::ji("check")`
6. .red[Space] `r emo::ji("check")`
7. .red[Remove Repetition] `r emo::ji("check")`
8. .red[Outliers]
9. .red[Group Similar] `r emo::ji("check")`
10. .red[Visualizations]
11. .red[Key Point(s)] `r emo::ji("check")`
12. .red[Annotations]
13. .red[Caption/Title] `r emo::ji("check")`
]]
---
class: segue
# Where We are Going
A Religious Experience
Playing with Babies
Fun with Cameras in the Surgical Theater
What is going on in Florida?
---
# Categorical Data Analysis
.pull-left[
+ One of the best-written statistics books:
*An Introduction to Categorical Data Analysis* by Alan Agresti
]
.pull-right[
![:scale 50%](images/Agresti.jpg)
]
https://raymondbalise.github.io/Agresti_IntroToCategorical/
https://github.com/RaymondBalise/Agresti_IntroToCategorical
---
# Good Tables vs. Really???
.pull-left[
The physical book has lovely tables printed on horribly thin paper:
<br><br>
.center[![:scale 100%](images/Agresti_physical.jpg)]
]
.pull-right[
The online version through the UM library is not beautiful:
<br><br>
.center[![:scale 100%](images/Agresti_online.jpg)]
]
---
# Critique - Agresti Book
.pull-left[
The physical book has lovely tables printed on horribly thin paper:
<br><br>
.center[![:scale 100%](images/Agresti_physical.jpg)]
]
.pull-right[.small[
1. .red[Heads] `r emo::ji("check")`
2. .red[Subtle Dividers] `r emo::ji("check")`
3. .red[Right-Align Numbers] `r emo::ji("check")`
4. .red[Left-Align Text] `r emo::ji("check")`
5. .red[Precision] `r emo::ji("check")`
6. .red[Space] `r emo::ji("check")`
7. .red[Remove Repetition] `r emo::ji("check")`
8. .red[Outliers]
9. .red[Group Similar] `r emo::ji("check")`
10. .red[Visualizations]
11. .red[Key Point(s)] `r emo::ji("x")`
12. .red[Annotations]
13. .red[Caption/Title] `r emo::ji("check")`
]]
---
# Critique - Agresti Online
.pull-left[
The physical book has lovely tables printed on horribly thin paper:
<br><br>
.center[![:scale 100%](images/Agresti_online.jpg)]
]
.pull-right[.small[
1. .red[Heads] `r emo::ji("check")`
2. .red[Subtle Dividers] `r emo::ji("x")`
3. .red[Right-Align Numbers] `r emo::ji("check")`
4. .red[Left-Align Text] `r emo::ji("check")`
5. .red[Precision] `r emo::ji("check")`
6. .red[Space] `r emo::ji("x")`
7. .red[Remove Repetition] `r emo::ji("check")`
8. .red[Outliers]
9. .red[Group Similar] `r emo::ji("check")`
10. .red[Visualizations]
11. .red[Key Point(s)] `r emo::ji("x")`
12. .red[Annotations]
13. .red[Caption/Title] `r emo::ji("check")`
]]
---
# The .blue[`medicaldata`] Package
There is a dataset called .blue[`opt`] that has information from a controlled trial looking to see if treatment for periodontal disease can reduce the risk of preterm and low birth weight babies.
.center[![:scale 70%](images/NEJM_baby.jpg)]
---
## NEJM Style Table 1
.pull-left-60[![:scale 70%](images/NEJM_table1.jpg)]
.pull-left-36[.small[
1. .red[Heads] `r emo::ji("check")`
2. .red[Subtle Dividers] `r emo::ji("check")`
3. .red[Right-Align Numbers] `r emo::ji("check")`
4. .red[Left-Align Text] `r emo::ji("check")`
5. .red[Precision] `r emo::ji("check")`
6. .red[Space] `r emo::ji("check")`
7. .red[Remove Repetition] `r emo::ji("check")`
8. .red[Outliers]
9. .red[Group Similar] `r emo::ji("check")`
10. .red[Visualizations]
11. .red[Key Point(s)] `r emo::ji("x")`
12. .red[Annotations] `r emo::ji("check")`
13. .red[Caption/Title] `r emo::ji("check")`
]]
---
### Device Clinical Trial - Laryngoscope Camera
.pull-left-60[
.center[
![:scale 80%](images/scope_pdf.jpg)
]
* How hard is it to replicate these and/or make an interactive summary?
]
.pull-right-36[.small[
1. .red[Heads] `r emo::ji("check")`
2. .red[Subtle Dividers] `r emo::ji("check")`
3. .red[Right-Align Numbers] `r emo::ji("x")`
4. .red[Left-Align Text] `r emo::ji("check")`
5. .red[Precision] `r emo::ji("check")`
6. .red[Space] `r emo::ji("shrug")`
7. .red[Remove Repetition] `r emo::ji("check")`
8. .red[Outliers]
9. .red[Group Similar] `r emo::ji("check")`
10. .red[Visualizations]
11. .red[Key Point(s)] `r emo::ji("check")`
12. .red[Annotations] `r emo::ji("check")`
13. .red[Caption/Title] `r emo::ji("check")`
]]
---
# What is going on in Florida?
.pull-left[.center[![:scale 100%](images/urbanRuralMap.jpg)]]
.pull-right[.center[![:scale 45%](images/florida_population.jpg)]]
.tiny[
https://www.floridahealth.gov/provider-and-partner-resources/community-health-workers/health-professional-shortage-designations/Rural%20Counties%20Map%202016.pdf
https://www.flhealthcharts.gov/FLQUERY_New/Population/Count#
]
---
class: segue
# So Many Tools ... So Little Time
---
# I wish there was a "best" tool.
+ You have a lot of package options for making static (i.e., Word, PDF or HTML) and dynamic (i.e., HTML) publication-ready tables.
+ All packages make web-friendly graphics.
+ Others make static graphics that are beautifully formatted for the the web: .blue[`gt`], .blue[`table1`], .blue[`gtsummary`], .blue[`kableExtra`].
+ Yet others make static tables that look great in Word: .blue[`flextable`].
+ Some are ideal for interactive web content: .blue[`dt`], .blue[`reactable`]
---
# Output for Packages that Make Tables
Not all packages support all R Markdown output formats.
.pull-left-60[
```{r supported, echo=FALSE}
library(gt)
path_figure <- list(
"img/icons8-smiling-100.png",
"img/icons8-neutral-100.png",
"img/icons8-disappointed-100.png",
"img/icons8-no-entry-100.png",
"img/icons8-under-construction-100.png",
"img/icons8-camera-100.png"
)
list(
printer = c(
"tibble", "kable", "kableExtra", "gt", "flextable", "huxtable", "dt", "reactable"
),
output = c("HTML", "PDF", "RTF", "Word")
) %>%
purrr::cross_df() %>%
dplyr::mutate(
rating = dplyr::case_when(
printer == "gt" & output == "HTML" ~ 1, # good output
printer == "gt" & output %in% c("PDF", "RTF") ~ 5, # under construction
printer == "gt" & output == "Word" ~ 4, # not supported
printer == "kable" ~ 2, # okay output
printer == "flextable" & output != "RTF" ~ 1, # good output
printer == "flextable" & output == "RTF" ~ 4, # not supported
printer == "kableExtra" & output %in% c("PDF", "HTML") ~ 1, # good output
printer == "kableExtra" & output %in% c("RTF", "Word") ~ 4, # not supported
printer == "huxtable" ~ 1, # good output
printer == "tibble" ~ 3, # not great
printer == "reactable" & output == "HTML" ~ 1, # good output
printer == "reactable" & output %in% c("RTF", "Word") ~ 4, # not supported
printer == "reactable" & output == "PDF" ~ 6, # picture
printer == "dt" & output == "HTML" ~ 1, # good output
printer == "dt" & output == "PDF" ~ 6, # picture
printer == "dt" & output %in% c("RTF", "Word") ~ 4, # not supported
) %>%
factor()
) %>%
tidyr::pivot_wider(id_cols = printer, names_from = output, values_from = rating) %>%
dplyr::mutate(
link = dplyr::case_when(
printer == "gt" ~
"[gt](https://gt.rstudio.com/index.html)",
printer == "kable" ~
"[kable](https://bookdown.org/yihui/rmarkdown-cookbook/kable.html)",
printer == "flextable" ~
"[flextable](https://davidgohel.github.io/flextable/articles/overview.html)",
printer == "kableExtra" ~
"[kableExtra](http://haozhu233.github.io/kableExtra/)",
printer == "huxtable" ~
"[huxtable](https://hughjonesd.github.io/huxtable/)",
printer == "tibble" ~
"[tibble](https://tibble.tidyverse.org/)",
printer == "reactable" ~
"[reactable](https://glin.github.io/reactable/index.html)",
printer == "dt" ~
"[DT](https://rstudio.github.io/DT/)"
),
fns = dplyr::case_when(
printer == "gt" ~ "`gt()`",
printer == "kable" ~ "`kable()`",
printer == "flextable" ~ "`flextable()`",
printer == "kableExtra" ~ "`kbl() + stuff`",
printer == "huxtable" ~ "`huxtable()`",
printer == "tibble" ~ "`tibble()`",
printer == "reactable" ~ "`reactable()`",
printer == "dt" ~ "`datatable()`",
)
) %>%
gt() %>%
cols_move_to_start(columns = c(link, fns)) %>%
cols_hide(columns = c(printer)) %>%
cols_label(
link = md("**Print Engine**"),
fns = md("**Function**"),
HTML = md("**HTML**"), PDF = md("**PDF**"),
RTF = md("**RTF**"), Word = md("**Word**")
) %>%
fmt_markdown(columns = c(fns, link)) %>%
data_color(
columns = c(HTML, PDF, RTF, Word),
colors = scales::col_factor(
palette = c(
"#D1B3F9", "#bae1ff", "#ffb3ba", "#ffdfba", "#ffffba", "#baffc9"
),
domain = NULL,
reverse = TRUE
),
alpha = 0.8
) %>%
text_transform(
locations = cells_body(columns = c(HTML, PDF, RTF, Word)),
fn = function(x) {
dplyr::case_when(
x == 1 ~ local_image(filename = path_figure[[1]]),
x == 2 ~ local_image(filename = path_figure[[2]]),
x == 3 ~ local_image(filename = path_figure[[3]]),
x == 4 ~ local_image(filename = path_figure[[4]]),
x == 5 ~ local_image(filename = path_figure[[5]]),
x == 6 ~ local_image(filename = path_figure[[6]])
)
}
) %>%
cols_width(
c(HTML, PDF, RTF, Word) ~ px(60),
c(link) ~ px(110),
c(link, fns) ~ px(200)
)
```
]
.pull-right-36[
```{r supported-key, echo=FALSE}
tibble::tibble(
figure = 1:6,
desc = c(
"Output fully supported",
"Formatted output, but missing indentation, footnotes, spanning headers",
"No formatted output",
"Output not supported",
"Under development",
"Image of first page with controls"
)
) %>%
gt() %>%
cols_label(figure = md("**Key**"), desc = "") %>%
data_color(
columns = c(figure),
colors = scales::col_factor(
palette = c(
"#D1B3F9", "#bae1ff", "#ffb3ba", "#ffdfba", "#ffffba", "#baffc9"
),
domain = NULL,
reverse = TRUE
),
alpha = 0.8
) %>%
text_transform(
locations = cells_body(columns = c(figure)),
fn = function(x) {
dplyr::case_when(
x == 1 ~ local_image(filename = path_figure[[1]], height = 20),
x == 2 ~ local_image(filename = path_figure[[2]], height = 20),
x == 3 ~ local_image(filename = path_figure[[3]], height = 20),
x == 4 ~ local_image(filename = path_figure[[4]], height = 20),
x == 5 ~ local_image(filename = path_figure[[5]], height = 20),
x == 6 ~ local_image(filename = path_figure[[6]], height = 20),
)
}
) %>%
tab_options(table.font.size = "x-small", data_row.padding = px(3))
```
.tiny[.center[Thanks to Daniel D. Sjoberg for the table code.]]
.pull-down[.tinyRight[
Icons from [icons8](https://icons8.com/)]]
]
---
class: segue
# Make a Table
When You Already Have Preprocessed the Data
A religious experience...
---
# Categorical Data Analysis
.pull-left[
+ *An Introduction to Categorical Data Analysis* by Alan Agresti has solid SAS code.
+ A couple years ago, I decided to try to replicate everything in R.
.center[![:scale 100%](images/agresti_balise.jpg)]
]
.pull-right[
![:scale 50%](images/Agresti.jpg)
]
---
# Agresti in R
+ This is quick code for exploratory data analysis but we can do a lot better.
```{r old-table, comment=NA, echo=TRUE, eval=FALSE}
table2_1 <- data.frame(
Gender = c("Female", "Female", "Male", "Male"),
Belief = c(" Yes", "No", " Yes", "No"),
Count = c(1230, 357, 859, 413)
)
addmargins(xtabs(Count ~ Gender + Belief, table2_1))
```
.pull-left-60[.center[
```{r old-table-output, echo=FALSE}
table2_1 <- data.frame(
Gender = c("Female", "Female", "Male", "Male"),
Belief = c(" Yes", "No", " Yes", "No"),
Count = c(1230, 357, 859, 413)
)
addmargins(xtabs(Count ~ Gender + Belief, table2_1))
```
]]
Notice that I used a space before "Y" in "Yes" to set the order.
---
# .blue[`tibble`] - Not Exactly Publication Ready....
```{r new-table-2-1, eval=FALSE}
`Table 2.1` <-
xtabs(Count ~ Gender + Belief, table2_1) %>%
addmargins() %>%
as_tibble()
`Table 2.1`
```
.center[
```{r new-table-2-1-output, echo=FALSE}
`Table 2.1` <-
xtabs(Count ~ Gender + Belief, table2_1) %>%
addmargins() %>%
as_tibble()
`Table 2.1`
```
]
---
# Pivot to Make a Table Wide - .blue[`tibble`] `r gt::local_image(filename = path_figure[[3]])`
The `Table 2.1` data set was saved with .blue[`as_tibble()`].
```{r make-wide}
wide <-
`Table 2.1` %>%
pivot_wider(id_cols = Gender, names_from = Belief, values_from = n) %>%
mutate(
Gender = if_else(Gender == "Sum", "Total", Gender)
) %>%
rename(
Yes = ` Yes`,
# I could also do: `No or Undecided` = No,
Total = Sum
)
wide
```
---
# .blue[`knitr::kable()`] `r gt::local_image(filename = path_figure[[2]])`
+ Drop that tibble into .blue[`kable()`] and add on pretty column names with the .blue[col.names=] argument.
```{r kable-show, eval=FALSE}
wide %>%
kable(
col.names = c("Gender", "Yes", "No or Undecided", "Total")
)
```
.center[![:scale 50%](images/kable.jpg)]
Not bad...
---
# .blue[`kableExtra::kbl()`] + stuff
```{r kable-code, echo=FALSE}
if ("flextable" %in% (.packages())) {
detach("package:flextable", unload = TRUE)
}
```
```{r kableExtra, eval=FALSE}
library(kableExtra)
wide %>%
kbl(
col.names = c("Gender", "Yes", "No or Undecided", "Total"),
align = c("l", "r", "c", "r")
) %>%
add_header_above(c(" ", "Belief in Afterlife" = 2, " ")) %>%
column_spec(3, width = "10em") %>% # make the 3rd column extra wide
footnote(
general = "Data from 2016 General Social Survey.",
general_title = "Source: ",
footnote_as_chunk = T, title_format = c("italic")
)
```
.center[![:scale 30%](images/almost.jpg)]
Closer, but not good...
---
# Add Some CSS
+ I am using the `xaringan` package to render slides, so I need a small tweak.
+ Web page formatting is done with CSS. Here I am adding instructions for things tagged as being in a table. I need to set them to have a white background.
---
# Adding CSS
.center[![:scale 100%](images/css.jpg)]
```{css, echo=FALSE, eval=TRUE}
.remark-slide thead, .remark-slide tr {
background-color: white;
}
.remark-slide thead, .remark-slide tfoot {
background-color: white;
}
```
```{r kableExtra-show, eval=FALSE}
library(kableExtra)
wide %>%
kbl(
col.names = c("Gender", "Yes", "No or Undecided", "Total"),
align = c("l", "r", "c", "r")
) %>%
add_header_above(c(" ", "Belief in Afterlife" = 2, " ")) %>%
column_spec(3, width = "10em") %>%
footnote(
general = "Data from 2016 General Social Survey.",
general_title = "Source: ",
footnote_as_chunk = T, title_format = c("italic")
)
```
---
# Close to Perfect - .blue[`kableExtra`] `r gt::local_image(filename = path_figure[[1]])`
.small[
```{css, echo=F}
.remark-slide thead, .remark-slide tr:nth-child(2n) {
background-color: white;
}
.remark-slide thead, .remark-slide tfoot {
background-color: white;
}
```
```{r kableExtra-run, echo=FALSE}
suppressPackageStartupMessages(library(kableExtra))
wide %>%
kbl(
col.names = c("Gender", "Yes", "No or Undecided", "Total"),
align = c("l", "r", "c", "r")
) %>%
add_header_above(c(" ", "Belief in Afterlife" = 2, " ")) %>%
column_spec(3, width = "10em") %>%
footnote(
general = "Data from 2016 General Social Survey.",
general_title = "Source: ",
footnote_as_chunk = T, title_format = c("italic")
)
detach("package:kableExtra", unload = TRUE)
```
]
---
# How did I figure that out?
+ The .blue[`kableExtra`] documentation does not show the striping behavior...
+ So I tried to simplify.
+ I copied the code into a vanilla HTML R Markdown file.
+ It didn't include the stripes.
+ I did a Google search for .blue[`xaringan kableExtra`] formatting
+ It led me to this post which included the CSS:
.small[.center[https://stackoverflow.com/questions/55319141/xaringan-kableextrakable-styling-and-wider-tables]]
+ StackOverflow is your friend.
+ To learn how to find CSS elements, watch this:
.small[
.center[https://medium.com/@HadrienD/how-to-customize-font-size-in-r-markdown-documents-f5adff36e2cc]]
---
# .blue[`gt::gt()`]
+ RStudio has been working on GT for years...
```{r gt-basic}
library(gt)
wide %>%
gt()
```
---
# .blue[`gt::gt()`] Code Duplicates the Book $_1$ `r gt::local_image(filename = path_figure[[1]])`
```{r gt-show, eval=FALSE}
library(gt)
wide %>%
gt() %>%
tab_header(
title = "Table 2.1 Cross-classification of belief in afterlife by gender."
) %>%
tab_spanner(
label = "Belief in the Afterlife",
columns = 2:3
) %>%
tab_source_note(
source_note = "<em>Source:</em> Data from 2016 General Social Survey."
) %>%
tab_options(
table_body.hlines.color = "white",
table_body.border.bottom.color = "#D3D3D3",
table.border.bottom.color = "white"
)
```
---
# .blue[`gt::gt()`] Code Duplicates the Book $_2$ `r gt::local_image(filename = path_figure[[1]])`
.center[![:scale 50%](images/Agresti_physical.jpg)]
```{r gt-code, eval=TRUE, echo=FALSE}
library(gt)
wide %>%
gt() %>%
tab_header(
title = "Table 2.1 Cross-classification of belief in afterlife by gender."
) %>%
tab_spanner(
label = "Belief in the Afterlife",
columns = 2:3
) %>%
cols_align(
align = "center",
columns = c(Yes, No)
) %>%
cols_label(
No = md("No or Undecided")
) %>%
tab_source_note(
source_note = "<em>Source:</em> Data from 2016 General Social Survey."
) %>%
tab_options(
table_body.hlines.color = "white",
table_body.border.bottom.color = "#D3D3D3",
table.border.bottom.color = "white",
table.border.top.color = "white"
)
```
---
# GT and Word
.pull-left-60[
+ People have been asking for a direct export into Word for *years*.
+ Currently, you get nothing when you knit. `r emo::ji("angry_face")`
+ You can copy and paste GT tables from HTML output into a Word file. `r emo::ji("nauseated_face")`
+ I hope something in Quarto is going to fix it. `r emo::ji("pray")`
]
.pull-right-36[
.center[![:scale 70%](images/gt_word.jpg)]
]
---
# Clean Exports into Word
I know of two options:
+ The .blue[`flextable`] package is what I have used for hardcore tables.
+ I have been using it for years and I still think it is work.
+ Search my Agresti notes on GitHub for examples: https://github.com/RaymondBalise/Agresti_IntroToCategorical
+ https://ardata-fr.github.io/flextable-book/index.html
+ I discovered the .blue[`huxtable`] package in 2022 and I am exploring it.
---
# .blue[`flextable::flextable()`] $_1$
+ The weird thing is that you will want to specify the header first.
+ Add a value for every variable/column in every row of the header.
+ If you put the same words into multiple rows (like "Gender" and "Total" in the example below), the values can be merged later with .blue[`merge_*()`] commands.
```{r flex-head}
suppressPackageStartupMessages(library(flextable))
my_header <- data.frame(
col_keys = colnames(wide),
line1 = c("Gender", rep("Belief in the Afterlife", 2), "Total"),
# line2 is Gender, Yes, No, Total
line2 = colnames(wide)
)
```
---
# .blue[`flextable::flextable()`] $_2$
.small[
+ You specify the columns using the `col_keys` that you previously defined in the data frame and then tell it to use the data frame to make the columns.
+ Notice the merging of the cells with identical content in the header.
+ Column 1 (Gender) will be left-aligned. The rest of the columns are centered. Sadly, .blue[`flextable`] can not decimal-align.
]
```{r flex-show, eval=FALSE}
wide %>%
flextable(col_keys = my_header$col_keys) %>%
set_header_df(
mapping = my_header,
key = "col_keys"
) %>%
theme_booktabs() %>%
autofit(part = "all") %>%
align_nottext_col(align = "center") %>%
merge_h(part = "header") %>%
merge_v(part = "header") %>%
set_caption(caption = "Table 2.1 Cross-classification of belief in afterlife by gender.") %>%
add_footer_lines(values = "Source: Data from 2016 General Social Survey.")
```
---
# .blue[`flextable::flextable()`] $_3$
```{r flex-code, echo=FALSE}
wide %>%
flextable(col_keys = my_header$col_keys) %>%
set_header_df(
mapping = my_header,
key = "col_keys"
) %>%
theme_booktabs() %>%
autofit(part = "all") %>%
align_nottext_col(align = "center") %>%
merge_h(part = "header") %>%
merge_v(part = "header") %>%
set_caption(caption = "Table 2.1 Cross-classification of belief in afterlife by gender.") %>%
add_footer_lines(values = "Source: Data from 2016 General Social Survey.")
```