Data @ Reed

Making tables

In addition to presenting data graphically, you may wish to display summary data in some form of table. The default table printing in R is useful for data work, but may not be ideal for a final product. See below for two ways to output more appealing tables.

HTML output with kable

The knitr package has good functionality (via kablefor printing HTML tables. The basic format is

kable(x, format = 'html')

Most of the good parts of this format come with the kableExtra package, however. You can use the kable_styling function to customize the look of your table.

library(kableExtra)
head(iris) %>%
  kable() %>%
  kable_styling(bootstrap_options = "striped",
                full_width = FALSE,
                position = "center")

PDF output with xtable

For a PDF document, typically a nice LaTeX table will be a good fit, which you can create with xtable.

library(xtable)
data(tli)
print(xtable(head(tli)), type = "latex", booktabs = TRUE)
Example pdf table

This table specifically is an image from a knitted PDF version - if you use xtable with an HTML output, the resulting table will not format as nicely.

To use xtable in an R markdown chunk, add the option results = 'asis' to your chunk. One nice table style uses the booktabs setting, which you can invoke by adding the following line to the YAML header of your Markdown file:

header-includes:
   - \usepackage{booktabs}

The above code makes sure your file can access the LaTeX package bookdown when it knits. (This is important because bookdown contains instructions for creating that style.)