Learn R Programming

⚠️There's a newer version (2.4.3) of this package.Take me there.

Basics

The htmlTable package is intended for generating tables using HTML formatting. This format is compatible with Markdown when used for HTML-output. The most basic table can easily be created by just passing a matrix or a data.frame to the htmlTable-function:

library(htmlTable)
# A simple output
output <- matrix(1:4,
                 ncol=2,
                 dimnames = list(list("Row 1", "Row 2"),
                                 list("Column 1", "Column 2")))
htmlTable(output)

As of version 1.0.2 you no longer need to specify results='asis' for each knitr chunk.

Advanced

While it may be sufficient for basic tables a more advanced layout is often needed in medical publications with elements such as:

  • row groups
  • column spanners
  • table spanners
  • caption
  • table footer
  • zebra coloring (also know as banding):
    • rows
    • columns

As many journals require that a MS Word-document is submitted it is furthermore also important that the table imports correctly to a word processor, i.e. that the table doesn't only look nice in a web browser but also in the final document. The htmlTable-function is written for all these purposes.

Note: Due to GitHub CSS-styles the rows get automatically zebra-striped (in a bad way), borders get overridden and I haven't been able to figure out how to change this. See the vignette for a correct example: vignette("general", package = "htmlTable")

For demonstration purposes we will setup a basic matrix:

mx <-
  matrix(ncol=6, nrow=8)
rownames(mx) <- paste(c("1st", "2nd",
                        "3rd",
                        paste0(4:8, "th")),
                      "row")
colnames(mx) <- paste(c("1st", "2nd",
                        "3rd", 
                        paste0(4:6, "th")),
                      "hdr")

for (nr in 1:nrow(mx)){
  for (nc in 1:ncol(mx)){
    mx[nr, nc] <-
      paste0(nr, ":", nc)
  }
}

Row groups

The purpose of the row groups is to group variables that belong to the same group, e.g. a factored variable with more than two levels often benefit from grouping variables together.

htmlTable(mx, 
          rgroup = paste("Group", LETTERS[1:3]),
          n.rgroup = c(2,4,nrow(mx) - 6))

We can easily mix row groups with regular variables by having an empty row group name "":

htmlTable(mx, 
          rgroup = c(paste("Group", LETTERS[1:2]), ""),
          n.rgroup = c(2,4,nrow(mx) - 6))

When mixing row groups with variables without row groups we may want to omit the bold formatting of the row group label:

htmlTable(mx, 
          css.rgroup = "",
          rgroup = c(paste("Group", LETTERS[1:2]), ""),
          n.rgroup = c(2,4,nrow(mx) - 6))

Column spanners

A column spanner spans 2 or more columns:

htmlTable(mx,
          cgroup = c("Cgroup 1", "Cgroup 2"),
          n.cgroup = c(2,4))

It can sometimes be convenient to have column spanners in multiple levels:

htmlTable(mx,
          cgroup = rbind(c("", "Column spanners", NA),
                         c("", "Cgroup 1", "Cgroup 2")),
          n.cgroup = rbind(c(1,2,NA),
                           c(2,2,2)))

Above example allows the column spanner to be a sum of the underlying cgroups (see n.cgroup), this is not required by the function:

htmlTable(mx,
          cgroup = rbind(c("", "Column spanners", NA),
                         c("", "Cgroup 1", "Cgroup 2")),
          n.cgroup = rbind(c(1,5,NA),
                           c(2,1,3)))

Table spanners

A table spanner is similar to rgroup but has the primary purpose of combining 2 or more tables with the same columns into one:

htmlTable(mx, 
          tspanner = paste("Spanner", LETTERS[1:3]),
          n.tspanner = c(2,4,nrow(mx) - 6))

Table caption

The table caption is simply the table description and can be either located above or below the table:

htmlTable(mx[1:2,1:2], 
          caption="A table caption above")
htmlTable(mx[1:2,1:2], 
          pos.caption = "bottom",
          caption="A table caption below")

A more interesting detail that the function allows for is table numbering, initialized by:

options(table_counter = TRUE)
htmlTable(mx[1:2,1:2], 
          caption="A table caption with a numbering")

As we often want to reference the table number in the text there are two associated functions:

tblNoLast()
## [1] 1
tblNoNext()
## [1] 2

Table footer

The footer usually contains specifics regarding variables and is always located at the foot of the table:

htmlTable(mx[1:2,1:2], 
          tfoot="A table footer")

Putting it all together

Now if we want to do everything in one table it may look like this:

htmlTable(mx, 
          align="r",
          rgroup = paste("Group", LETTERS[1:3]),
          n.rgroup = c(2,4,nrow(mx) - 6),
          cgroup = rbind(c("", "Column spanners", NA),
                         c("", "Cgroup 1", "Cgroup 2&dagger;")),
          n.cgroup = rbind(c(1,2,NA),
                           c(2,2,2)),
          caption="A table with column spanners, row groups, and zebra striping",
          tfoot="&dagger; A table footer commment",
          cspan.rgroup = 2,
          col.columns = c(rep("none", 2),
                          rep("#F5FBFF", 4)),
          col.rgroup = c("none", "#F7F7F7"),
          css.cell = "padding-left: .5em; padding-right: .2em;")

Copy Link

Version

Install

install.packages('htmlTable')

Monthly Downloads

162,711

Version

1.13.1

License

GPL (>= 3)

Maintainer

Max Gordon

Last Published

January 7th, 2019

Functions in htmlTable (1.13.1)

htmlTableWidget

htmlTable with pagination widget
prGetThead

Renders the table head (thead)
prAddSemicolon2StrEnd

Add a ; at the end
prIsNotebook

Detects if the call is made from within an RStudio Rmd file or a file with the html_notebook output set.
prPrepareCgroup

Prepares the cgroup argument
prAttr4RgroupAdd

Get the add attribute element
prPrepareColors

Prepares the alternating colors
prGetAlign

Gets alignment
prGetCgroupHeader

Retrieve a header row
prMergeClr

Merges multiple colors
txtPval

Formats the p-values
prPrepareAlign

Prepares the align to match the columns
txtRound

A convenient rounding function
tblNoNext

Gets the next table number
tidyHtmlTable

Generate an htmlTable using a ggplot2-like interface
htmlTableWidget-shiny

Shiny bindings for htmlTableWidget
htmlTable

Outputting HTML tables
prGetScriptString

Gets a string with all the scripts merged into one script tag
prGetStyle

Gets the CSS style element
prTblNo

Gets the table counter string
pvalueFormatter

prGetRgroupLine

Gets the number of rgroup htmlLine
prGetRowlabelPos

Gets the rowlabel position
SCB

Average age in Sweden
outputInt

prAddCells

Add a cell
concatHtmlTables

Funciton for concatenating htmlTables
prEscapeHtml

Remove html entities from table
prConvertDfFactors

Convert all factors to characters to print them as they expected
splitLines4Table

prPrepareCss

Prepares the cell style
tblNoLast

Gets the last table number
prSkipRownames

Returns if rownames should be printed for the htmlTable
vector2string

Collapse vector to string
txtInt

SI or English formatting of an integer
txtMergeLines

A merges lines while preserving the line break for html/LaTeX
interactiveTable

An interactive table that allows you to limit the size of boxes