23 Communication—table formatting
23.1 Reading & reference
Garrett Grolemund and Hadley Wickham, R for Data Science
- “Communication” section, Chapters 26 “Introduction” to 29 “R Markdown formats”
R Markdown
Yihui Xie, Christophe Dervieux, Emily Riederer, “The kableExtra package”, R Markdown Cookbook
Packages:
kableExtra
Hao Zhu, Create Awesome HTML Table with knitr::kable and kableExtra
Hao Zhu, Using kableExtra in Bookdown
Yihui Xie, Christophe Dervieux, Emily Riederer, “The kableExtra package”, R Markdown Cookbook
flextable
{flextable} - flextable R package reference
David Gohel, flextable book
gt
Introduction to Creating gt Tables (from the package site)
23.2 Introduction
The look of the default table in R markdown is not all that attractive. Here’s a summary table of the Oakland Athletics’ seasons from 1999-2008.
## # A tibble: 10 x 8
## year_num tm attend_g est_payroll pay_index w l w_l_percent
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 1999 OAK 17711 24831833 49.5 87 75 0.537
## 2 2000 OAK 19799 33172333 59.0 91 70 0.565
## 3 2001 OAK 26337 33810750 51.5 102 60 0.63
## 4 2002 OAK 26788 40004167 59.2 103 59 0.636
## 5 2003 OAK 27365 50260834 70.8 96 66 0.593
## 6 2004 OAK 27179 59425667 85.8 91 71 0.562
## 7 2005 OAK 26038 55425762 76.0 88 74 0.543
## 8 2006 OAK 24403 64843079 83.2 93 69 0.574
## 9 2007 OAK 23726 79366940 95.3 76 86 0.469
## 10 2008 OAK 20559 47967126 53.4 75 86 0.466
There are a few R packages that allow us to format a table like this, ready for publication. Here we will take a quick look at two of them. Both have many, many more options for formatting; see the reference materials at the top of this chapter for those details.
23.3 The kable package
First, {kableExtra} is an extension to the {kable} tool that is part of “knitting” our R Markdown files.
library(kableExtra)
# print table with {kableExtra} formatting
oakland_99 %>%
# create table, add title
kable(caption = "Oakland Athletics, 1999-2008") %>%
kable_styling(bootstrap_options = "striped", font_size = 10) %>%
# make variable names bold and large
row_spec(0, bold = T, font_size = 14) %>%
# make 2002 season (row 4) bold
row_spec(4, bold = T)
year_num | tm | attend_g | est_payroll | pay_index | w | l | w_l_percent |
---|---|---|---|---|---|---|---|
1999 | OAK | 17711 | 24831833 | 49.54511 | 87 | 75 | 0.537 |
2000 | OAK | 19799 | 33172333 | 59.03364 | 91 | 70 | 0.565 |
2001 | OAK | 26337 | 33810750 | 51.51234 | 102 | 60 | 0.630 |
2002 | OAK | 26788 | 40004167 | 59.15217 | 103 | 59 | 0.636 |
2003 | OAK | 27365 | 50260834 | 70.82774 | 96 | 66 | 0.593 |
2004 | OAK | 27179 | 59425667 | 85.76543 | 91 | 71 | 0.562 |
2005 | OAK | 26038 | 55425762 | 75.95992 | 88 | 74 | 0.543 |
2006 | OAK | 24403 | 64843079 | 83.20773 | 93 | 69 | 0.574 |
2007 | OAK | 23726 | 79366940 | 95.27085 | 76 | 86 | 0.469 |
2008 | OAK | 20559 | 47967126 | 53.41372 | 75 | 86 | 0.466 |