Using latexTable() with R Markdown and Rnw documents

It is easy to use latexTable() in R Markdown documents, provided that you are generating LaTeX or PDF files from those R Markdown documents. To do so, you need to take only two steps: load a file via the in_header option for R Markdown documents, and wrap your latexTable() output in the raw_latex() command that is provided by the knitr package.

1. Headers for R Markdown documents

To use latexTable() in R Markdown documents, certain LaTeX packages must be loaded: the afterpage, array, booktabs, caption, numprint and ragged2e packages. Depending on the options that you specify in your latexTable() call, you may also need to load the afterpage, float, and pdflscape packages.

The Bullock package comes with a file, latexTable_RMarkdown_preamble.tex, that loads all of these packages. Thus, to load the packages, you need only tell R Markdown to load latexTable_RMarkdown_preamble.tex. The best way to do this is by using the in_header option in the header of your R Markdown document. The header should look like this:

---
title: "Test latexTable() Output"
output: 
  pdf_document:
    includes:
      in_header: !expr system.file("latexTable_RMarkdown_preamble.tex", package = "Bullock", mustWork = TRUE)
---

2. Inserting latexTable() output into an R Markdown document

To insert latexTable() output into your R Markdown document, just wrap the output in a raw_latex() command:

library(Bullock)
library(knitr)
myTable <- latexTable(matrix(1:16, nrow = 4))
raw_latex(myTable)

Remember that if you are using multiple tables, you will need to specify a unique LaTeX name for each one (by using the commandName argument in your latexTable() calls).

3. Inserting latexTable() output into a Sweave / Rnw document.

LaTeX documents that contain embedded R code chunks are sometimes called “Sweave” documents, and they typically have the extension .Rnw. The procedure for embedding latexTable() output into these documents is just a little different:

<<myTable, echo = FALSE, results = "asis">>=
library(Bullock)
library(knitr)
myTable <- latexTable(matrix(1:16, nrow = 4))
cat(myTable, sep = "\n")
@

4. Limitations

The most obvious limitation is that latexTable() cannot be used when generating HTML documents from R Markdown. It will work only when generating LaTeX or PDF from R Markdown.