Tables

Tables are used to present a large amount of data in a small form factor. Especially for summary statistics and variable descriptions they are usefull. There are different ways of making tables in R Markdown and I want to present you two.

Kable

The first involves the R package kableExtra and the function kable from knitr. With kable, you can create beautiful tables for summary statistics. The idea is to create a data frame which kable then transforms into a table. After creating the data frame with all the variables for which summary statistics are required, you can use lapply to return the desired statistics.

t_mean <- lapply(data, mean, na.rm = TRUE)
t_med <- lapply(data, median, na.rm = TRUE)
t_min <- lapply(data, min, na.rm = TRUE)
t_max <- lapply(data, max, na.rm = TRUE)

# The mean should be rounded
t_mean <- round(as.numeric(t_mean),1)

Then you want to create the table:

table <- cbind(Mean = t_mean, Median = t_med, Min = t_min, Max = t_max)

Which then can be used for kable:

library(kableExtra)
kable(table, format = "html", caption = "\\label{table1} Some caption.", # Or format = "latex" 
      booktab = TRUE) %>% 
   kable_styling(bootstrap_options = c("striped", "responsive"))
Table 1: Some caption.
Mean Median Min Max
Sepal.Length 5.8 5.8 4.3 7.9
Sepal.Width 3.1 3 2 4.4
Petal.Length 3.8 4.35 1 6.9
Petal.Width 1.2 1.3 0.1 2.5

This is a .html file, for your .pdf output you want to set the format = "latex", therefore R Markdown transforms the input of kable in a table which looks really good. The options of kableExtra are limitless and with the pipe operator %>% which comes with dplyr you can just keep on adding more specifications which can be found at kableExtra.

Pander