# HTML Tables

#### January 17, 2016

This short R Markdown document illustrates how to use tables in HTML.

## Initializing

First, you need to load tables. Packages that it uses print banner messages, so you’ll usually want to set a chunk option of message=FALSE.

library(tables)

The table is now constructed in the usual way.

X <- rnorm(125, sd=100)
Group <- factor(sample(letters[1:5], 125, rep=TRUE))
tab <- tabular( Group ~ (N=1)+Format(digits=2)*X*((Mean=mean) + Heading("Std Dev")*sd) )

In an R Markdown document, you don’t want each table to output the HTML document header, so turn off those options:

table_options(htmloptions(head=FALSE))

## Inserting a Table

There are two ways to insert a table into a knitr/rmarkdown document. Since tables version 0.8.4, you can just print the object, and it will be automatically formatted according to the current table_options():

tab
X
Group N Mean Std Dev
a 28 -2.6 96.8
b 19 -20.4 94.7
c 25 -23.3 102.9
d 29 -3.7 91.5
e 24 -6.9 113.9

The previous behaviour required an explicit call to the toHTML() function, and knitr option results = 'asis' for the chunk. To require the older method, use table_options(knit_print = FALSE):

table_options(knit_print = FALSE)
tab        # This chunk uses the default results = 'markup'
##
##           X
##  Group N  Mean  Std Dev
##  a     28  -2.6  96.8
##  b     19 -20.4  94.7
##  c     25 -23.3 102.9
##  d     29  -3.7  91.5
##  e     24  -6.9 113.9
toHTML(tab)  # This chunk uses results = 'asis'
X
Group N Mean Std Dev
a 28 -2.6 96.8
b 19 -20.4 94.7
c 25 -23.3 102.9
d 29 -3.7 91.5
e 24 -6.9 113.9

In either case, some styling information needs to be included in the document. Ideally this should be in the header, but it can be inserted anywhere by calling writeCSS with results = 'asis':

writeCSS()

## Improving the Look

The default justification makes the columns of numbers look messy. You can set the justification to the right, but the headers look wrong:

table_options(htmloptions(head = FALSE, justification = "r", knit_print = TRUE))
tab
X
Group N Mean Std Dev
a 28 -2.6 96.8
b 19 -20.4 94.7
c 25 -23.3 102.9
d 29 -3.7 91.5
e 24 -6.9 113.9

The best look comes with the pad = TRUE option. This adds nonbreaking spaces around the numbers so that centering looks good. It also changes the hyphens to proper minus signs:

table_options(htmloptions(head = FALSE, justification = "c", pad = TRUE))
tab
X
Group N Mean Std Dev
a 28   −2.6   96.8
b 19  −20.4   94.7
c 25  −23.3  102.9
d 29   −3.7   91.5
e 24   −6.9  113.9

Unfortunately, if you cut this table and paste it into a spreadsheet, the spaces and minus signs probably won’t be understood. I don’t know how to get everything we want :-(.