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?
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}
Related
I'd like to create a report, but my report need to be start with a logo. In my example, I try to do :
Here is the .rmd file (say, cylinder.rmd)
---
```{r echo=FALSE, out.width = "30%", fig.align = "center"}
knitr::include_graphics("R_logo.png")
```
title: "cylinder_report"
author: "author_name"
date: "2023-01-25"
output: pdf_document
params:
cylinder: 0
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
df = mtcars
```
## Cylinder `r params$cylinder`
```{r output, echo=FALSE}
knitr::kable(df[df$cyl == params$cylinder,])
```
And my separated file is:
library(knitr)
library (rmarkdown)
data(mtcars)
cyls = unique(mtcars$cyl)
for(cyl in cyls) {
rmarkdown::render(
input = "cylinder.Rmd",
output_file = paste0("cylinder_report_", cyl),
params = list(cylinder = cyl)
)
}
#
This code doesn't work, but for better comprehension my desirable output must to be:
Please any help with it?
The solution was find in: https://bookdown.org/yihui/rmarkdown-cookbook/latex-logo.html
The .Rmd needs to be:
---
title: "cylinder_report"
author: "author_name"
date: "2023-01-25"
output: pdf_document
params:
cylinder: 0
header-includes:
- \usepackage{titling}
- \pretitle{\begin{center}
\includegraphics[width=2in,height=2in]{R_logo.png}\LARGE\\}
- \posttitle{\end{center}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
df = mtcars
```
## Cylinder `r params$cylinder`
```{r output, echo=FALSE}
knitr::kable(df[df$cyl == params$cylinder,])
```
I have a parametrized rmarkdown document based on Shiny inputs.
The rmarkdown pdf renders properly when the app runs locally. However when hosted on the shiny server it produces \end{landscape} at the end of each table.
Here is a snippet of the rmarkdown code:
---
title: "Custom Analysis Report"
date: "Last compiled on `r format(Sys.time(), '%d %B, %Y')`"
output:
pdf_document:
mainfont: Times New Roman
fontsize: 11pt
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{lscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
- \usepackage{xcolor}
always_allow_html: true
---
```{r setup, include=FALSE}
library(knitr)
library(kableExtra)
```
```{r echo = FALSE , warning = FALSE, message = FALSE, eval = TRUE , results='asis'}
if (nrow(org_profile_df1()) >= 1){
options(knitr.kable.NA = 'NA')
org_profile_df1() %>%
kable(align = "l",
format = "latex",
longtable = T,
booktabs = T,
caption = "Organizational Profile") %>%
kable_classic(full_width = F) %>%
# column_spec(1, bold = T, color = "red") %>%
kable_styling(latex_options = c("repeat_header", "bordered", "striped"),font_size = 4, position = "left",
#,"striped", "scale_down"),
repeat_header_continued = "\\textit{(Continued on Next Page...)}") %>%
#kable_paper(full_width = T) %>%
row_spec(0, bold = T) %>% landscape()
}
options(knitr.kable.NA = '-')
```
org_profile_df1() is a reactive dataset that is generated by shiny parameters. There are other such reactive datasets that get generated based on whether they exist or not (the if-statements). After every one of these tables a blank page with \end{landscape} appears (see also picture). However when I run the shiny app locally this does not appear. Only when the app is hosted on Shinyapps.io does this occur.
I have included a picture of a reactive table. There are special characters such as % and : in the reactviely generated tables.
In a larger report compiled with bookdown I used several kableExtra tables which included LaTex commands (e.g., to add italics, bullets to create a listing, and manually-added footnotes within the table).
When I copy the tables in a LaTex beamer presentation generated with rmarkdown::beamer_presentation, compilation unfortunately fails.
How to twist the kableExtra tables to include the LaTex commands?
MWE
---
title: "MWE"
subtitle: "Beamer presentation with R-markdown"
author: "Donald Duck"
institute: "some place"
date: "`r format(Sys.time(), '%B %d, %Y')`"
output:
bookdown::pdf_book:
base_format: rmarkdown::beamer_presentation
theme: "THEMENAME"
latex_engine: xelatex
toc: false
slide_level: 2
---
(ref:footnote-a) Text for footnote a
(ref:footnote-b) Text for footnote b
\renewcommand{\arraystretch}{1.3} <!-- increase line spacing for the table -->
```{r table-wLatex, echo=FALSE, fig.align="center", message=FALSE, warning=FALSE, out.width='66%'}
library(kableExtra)
library(dplyr)
# table with manually added footnotes within table
df <- data.frame(
col1 = c("Category 1", "Category 2"),
col2 = c(
"foo and \\emph{special foo}$^{a}$",
"bar and \n $\\boldsymbol{\\cdot}$ \\emph{random bar}$^{a}$\n $\\boldsymbol{\\cdot}$ \\emph{special bar}$^{b}$")
)
# header: add column names
names(df) <- c("Categories", "Description")
df %>%
mutate_all(linebreak) %>% # required for linebreaks to work
kable(
"latex",
# escape = FALSE, # needed to be able to include latex commands
booktabs=TRUE,
align = "l",
caption = "Caption Table with LaTex" # short caption for LoT
) %>%
kableExtra::footnote(
alphabet = c(
"(ref:footnote-a)",
"(ref:footnote-b)"
),
threeparttable = TRUE, # important! Else footnote runs beyond the table
footnote_as_chunk = TRUE, title_format = c("italic", "underline")
) %>%
column_spec(1, width = "11em") %>% # fix width column 1
column_spec(2, width = "27em") # fix width column 2
```
\renewcommand{\arraystretch}{1} <!-- reset row height/line spacing -->
Several LaTex packages had to be loaded for kableExtra table such that LaTex code can well be included inside.
To fix the column width, column_spec(1, width = "3cm") is better specified in cm instead of em (for the previous specification, table ran beyond the slide).
---
title: "LaTex code inside a kable table in an rmarkdown::beamer_presentation"
output:
bookdown::pdf_book:
base_format: rmarkdown::beamer_presentation
latex_engine: xelatex
toc: false
slide_level: 2
header-includes:
- \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[usenames,dvipsnames]{xcolor} # clashes, as loaded by markdown anyway
---
(ref:footnote-a) Text for footnote a
(ref:footnote-b) Text for footnote b
\renewcommand{\arraystretch}{1.3} <!-- increase line spacing for the table -->
```{r table-wLatex, echo=FALSE, fig.align="center", message=FALSE, warning=FALSE, out.width='30%'}
library(kableExtra)
library(dplyr)
# table with manually added footnotes within table
df <- data.frame(
col1 = c("Category 1", "Category 2"),
col2 = c(
"foo and \\emph{special foo}$^{a}$",
"bar and \n $\\boldsymbol{\\cdot}$ \\emph{random bar}$^{a}$\n $\\boldsymbol{\\cdot}$ \\emph{special bar}$^{b}$")
)
# header: add column names
names(df) <- c("Categories", "Description")
df %>%
mutate_all(linebreak) %>% # required for linebreaks to work
kable(
"latex",
escape = FALSE, # needed to be able to include latex commands
booktabs=TRUE,
align = "l",
caption = "Caption Table with LaTex" # short caption for LoT
) %>%
kableExtra::footnote(
alphabet = c(
"(ref:footnote-a)",
"(ref:footnote-b)"
),
threeparttable = TRUE, # important! Else footnote runs beyond the table
footnote_as_chunk = TRUE, title_format = c("italic", "underline")
) %>%
kable_styling( # for wide tables: scale them down to fit
full_width = F,
latex_options = c(
"scale_down"
)) %>%
column_spec(1, width = "3cm") %>% # fix width column 1
column_spec(2, width = "5cm") # fix width column 2
```
\renewcommand{\arraystretch}{1} <!-- reset row height/line spacing -->
---
title: "test_kableExtra"
date: "14/12/2018"
output:
pdf_document:
latex_engine: xelatex
includes:
in_header: head.tex
---
``` {r table, echo = FALSE}
library(tidyverse)
library(kableExtra)
table <- tibble(`Column title` = "lots of very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long text ")
kable(table, booktabs = T, caption = "Table title") %>%
kable_styling(full_width = F) %>%
column_spec(1, width = "5cm")
```
More text...
In head.tex:
\usepackage{float}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
I get the error ! LaTeX Error: \caption outside float.
If I remove caption = "Table title"
then I get this output
I don't understand why:
the column width has not been changed to 5cm,
why the text after the code chunk is centred,
why "\begin{tab..." and "\end{table} is coming up.
Thank you for any help!
I have written an Rmarkdown file that loads some data and generates a kableExtra table with some symbols and custom colors and lines, printing it to pdf.
It works when I open the Rmarkdown file and knit, and produces the exact output that I want. For various reasons I need to call this Rmarkdown file from another .R file.
However, when I do this (using the rmarkdown::render function), I get an error that doesn't occur when knitted directly from within the .Rmd file. Specifically, the errors are caused by setting background within the cell_spec function; removing this call to set the background color allows me to successfully render the .Rmd file from another file. The error is:
! Illegal parameter number in definition of \reserved#a.
<to be read again>
f
l.111 ...; background-color: #ffe6e6;" >1</span>}}
\\
Thanks so much for any advise.
Here is a complete Rmd file that reproduces the issue. The output when knitted directly from Rmd looks like this:
Here is the code.
---
title: ""
always_allow_html: yes
output:
pdf_document:
latex_engine: xelatex
geometry: margin=0.3in
header-includes:
- \usepackage[T1]{fontenc}
- \usepackage{array}
- \usepackage{booktabs}
- \usepackage{xcolor}
- \usepackage{makecell}
- \usepackage{longtable}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{hyperref}
- \setmainfont{Helvetica}
- \pagenumbering{gobble}
- \DeclareTextCommand{\nobreakspace}{TU}{\leavevmode\nobreak\ }
documentclass: article
classoption: a4paper
---
```{r, echo=FALSE, message = FALSE, warning = FALSE}
# Packages
suppressMessages(library(ggplot2))
suppressMessages(library(extrafont))
suppressMessages(library(dplyr))
suppressMessages(library(pander))
suppressMessages(library(kableExtra))
# Data
table_dat <- data.frame(latex_symbol = c("", "$\\blacktriangle$",
"$\\blacklozenge$", "$\\blacklozenge$",
"$\\bullet$", "+"),
color = c("#0c0000", "#ffde71", "#cb6f86",
"#0c0000", "#0c0000", "#0c0000"),
name = c("Thing 1", "Thing 2", "Thing 3",
"Thing 4", "Thing 5", "Thing 6"),
latex_font_size = c(14, 11, 8, 11, 16, 8),
value = c(1,"<0",3,4,5,6),
stringsAsFactors = FALSE)
fsize <- 12
bgcolor <- c(rep("#ffe6e6",2), rep("#ffffff", 4))
table_dat$value <- cell_spec(table_dat$value, background = bgcolor)
ktable <- table_dat %>%
rename(color_ = color) %>%
mutate(latex_symbol = cell_spec(latex_symbol, color = color_,
font_size = latex_font_size,
escape = FALSE,
format = "latex")) %>%
select(latex_symbol, name, value) %>%
kable(escape = FALSE, align = rep("l", 3),
booktabs = TRUE, format = "latex",
col.names = c("Symbol", "Name", "Value"),
linesep = "") %>%
row_spec(1:6, color = "darkgray") %>%
row_spec(0, bold = TRUE) %>%
column_spec(1, "5em") %>%
column_spec(2, "11em") %>%
column_spec(3, "4em") %>%
kable_styling(font_size = fsize) %>%
row_spec(1, bold = TRUE) %>%
row_spec(1:4, hline_after = TRUE)
```
```{r, echo=FALSE}
ktable
```
Note: the reason for so many packages being cited explicitly in the header is that I've had issues similar to this in the past that were solved by citing all of the packages associated with kable in my header before rendering. However, that didn't seem to solve my problem this time.