I'm trying to do something quite simple: generate reports in PDF format. Finally found a way that reproduces my issue. I need to use rmarkdown::render
to create reports based on data in GlobalEnv
. I am using the tinytex
package. Here is test.Rmd
:
---
title: "Untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(kableExtra)
library(tidyverse)
```
## R Markdown
```{r cars}
mtcars %>%
kable(booktabs = TRUE) %>%
kable_styling(latex_options = "striped")
```
"Knit" in RStudio seems to always work on this file, producing, as expected, the mtcars
dataframe, nicely formatted with kable()
Running rmarkdown::render("test.Rmd")
works on THE FIRST RUN, but NOT the second. It throws the error:
! LaTeX Error: Unknown float option `H'.
After this, "Knit" in RStudio produces the PDF, but R/knitr prints any warning/error messages from the rmarkdown::render("test.Rmd")
command.
Running rmarkdown::render("test.Rmd")
does not produce errors if the above code chunk is changed to
```{r cars}
mtcars %>%
kable()
```
I've elected to answer my own question because I've found a work-around that hopefully will not be necessary if someone finds the reason for the errors.
It seems that the PDF rendering engine does not recognize anything but the most basic LaTeX installation of tinytex
. I tried tinytex::tlmgr_install
to manually install the necessary LaTeX packages but all of them returned a "package already present" message.
I've added the following to my YAML in my Rmd:
header-includes:
- \usepackage{booktabs}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage[table]{xcolor}
I essentially added each \usepackage
line until I received no errors with the formatting I was looking for.
Both rmarkdown::render()
and knit
(Rstudio) work (and on my OWN code as well!):
---
title: "Untitled"
output: pdf_document
header-includes:
- \usepackage{booktabs}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage[table]{xcolor}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(kableExtra)
library(tidyverse)
```
## R Markdown
```{r cars}
mtcars %>%
kable(booktabs = TRUE) %>%
kable_styling(latex_options = "striped")
```
That didn't work for me. I was getting a clash in xcolor option. The solution as pointed out in page 3 : https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf
is to add :
options(kableExtra.latex.load_packages = FALSE)
and in the YAML :
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage{xcolor}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
Note that you can remove any packages that you don't need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With