Komal Rathi
Komal Rathi

Reputation: 4274

How to knit markdown to PDF using R command?

Trying to knit an Rmarkdown document to PDF from another R script. When I use the Rstudio interface, and hit Knit to PDF, it works perfectly fine and generates the PDF. But when I use the rmarkdown::render command, it gives me an error:

Markdown:

---
geometry: margin=0.75in
output:
  pdf_document: default
params: 
  set_title:
    value: "Sample"
editor_options: 
  chunk_output_type: console
header-includes:
     \usepackage{fancyhdr}
     \usepackage{graphicx}
---
---
title: `r params$set_title`
---

```{r load_libraries, include=FALSE, echo=FALSE}
suppressPackageStartupMessages({
  library(knitr)
  library(tidyverse)
  library(kableExtra)
})
```

\addtolength{\headheight}{2.0cm} 
\fancypagestyle{plain}{} 
\pagestyle{fancy} 
\renewcommand{\headrulewidth}{0pt}

```{r set_options, include = FALSE, echo = FALSE, warning = FALSE}
knitr::opts_chunk$set(comment = NA)
`%>%` <- dplyr::`%>%`
```

# 1. Table

```{r, echo = FALSE, message = FALSE, warning = FALSE}
# sample data frame
df <- data.frame(x = c("a", "b", "c"), 
                 y = c("a", "b", "c"))

# print table
kableExtra::kable(df, booktabs = T)  %>%
  kable_styling(full_width = TRUE, font_size = 8) %>%
  row_spec(0, bold = T) %>%
  column_spec(1, width = "1cm") %>%
  column_spec(2, width = "2cm")
```

This is how I am running it:

rmarkdown::render(input = "~/Projects/test.Rmd", 
                  params = list(set_title = "TEMP"), 
                  output_dir = "~/Desktop/", 
                  output_file = "test.pdf")

Error:

! LaTeX Error: Environment tabu undefined.

Error: LaTeX failed to compile /Users/rathik/Projects/test.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See test.log for more info.

The error is due to using kableExtra::kable because when I remove that function call, the error goes away. Any ideas how to resolve it?

Upvotes: 1

Views: 476

Answers (1)

Komal Rathi
Komal Rathi

Reputation: 4274

Thank you @Dirk, based on your suggestion and the LaTeX documentation, I added the following in the header and it seems to be working as expected:

\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
\usepackage{xcolor}

Upvotes: 1

Related Questions