23 Communication—table formatting

23.1 Reading & reference

Garrett Grolemund and Hadley Wickham, R for Data Science

R Markdown

Yihui Xie, Christophe Dervieux, Emily Riederer, “The kableExtra package”, R Markdown Cookbook

Packages:

kableExtra

flextable

gt

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.

oakland_99 <- mlb_pay_wl %>% 
  filter(tm == "OAK" & year_num < 2009)

oakland_99
## # 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) 
Table 23.1: Oakland Athletics, 1999-2008
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

23.4 The flextable package

Another table formating package is {flextable}.

library(flextable)

oakland_99 %>% 
  flextable() %>% 
  add_footer_row(values = "Source: baseball-reference.com", colwidths = 8)

-30-