# 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

To format a table in HTML, use the results = 'asis' knitr option. Before the first table in a document, also add a call to writeCSS() with results = 'asis':

writeCSS()
html(tab)
X
Group N Mean Std Dev
a 25 -38 110
b 22 -22 80
c 29 18 116
d 25 -33 88
e 24 -16 103

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"))
html(tab)
X
Group N Mean Std Dev
a 25 -38 110
b 22 -22 80
c 29 18 116
d 25 -33 88
e 24 -16 103

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))
html(tab)
X
Group N Mean Std Dev
a 25  −38  110
b 22  −22   80
c 29   18  116
d 25  −33   88
e 24  −16  103

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 :-(.

## Fine tuning

This document uses the default CSS from table_options()\$CSS. If you are producing an html_document, it should be okay. It does not look quite right in a slidy_presentation, and is no good at all in an ioslides_presentation. Furthermore, you might not agree with my design choices.

In any of these cases, you should substitute your own CSS. You will need to modify the default one, and can use it as the CSS argument to writeCSS(), or set it as a new default in table_options().

Here is the default setting:

<style>
#ID .Rtable thead, .Rtable .even {
background-color: inherit;
}
#ID .left   { text-align:left; }
#ID .center { text-align:center; }
#ID .right  { text-align:right; }
#ID .Rtable, #ID .Rtable thead {
border-collapse: collapse;
border-style: solid;
border-width: medium 0;
border-color: inherit;
}
#ID .Rtable th, #ID .Rtable td {
</style>
Note that the #ID values will be replaced with the id string given in writeCSS().