Fixing TeX problems in rmarkdown
If you use rmarkdown to produce pdfs, you may find you have problems with the latest RStudio when printing out LaTeX tables using R packages like xtable
or huxtable
. Recent versions of pandoc often escape TeX, resulting in errors when you try to compile your PDF.
You can check if this is happening to you by adding keep_tex: yes
to your document’s header:
---
...output:
pdf_document:
keep_tex: yes
---
If you then knit the document, it’ll produce the TeX file. If it contains output like:
\textbackslash{}begin\{table\}
where you would expect your table to be, then you have this problem.
The workaround is to add this line to your document’s header:
output:
pdf_document:
md_extensions: +raw_attribute
Then, before and after you print out TeX, you can add “raw” blocks to the output. This is a recent extension to pandoc, which ensures that content inside the block is not escaped. Raw attribute blocks look like this in the output.
```{=latex}
% TeX code here...```
For example, in your Rmarkdown file, you could have a chunk like:
```{r, results = "asis"}cat("```{=latex}")
xtable(head(mtcars))
cat("```")```
This will ensure that the TeX produced by xtable gets passed through pandoc, ready to be compiled into a PDF.
You will need pandoc version 2.0.0 or greater to use this trick. You can check your pandoc version using rmarkdown::pandoc_version().
If you use the R huxtable package to produce TeX, version 4.2.1, released yesterday, produces raw attribute blocks automatically in Rmarkdown documents. You will still have to add the +raw_attributes
to your document header, though. Hopefully, rmarkdown and/or knitr can find ways to automate this process.