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.
Related
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}
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 seen this post to include a background image to an R markdown report.
I have created a Shiny app to generate a pdf report:
shinyApp(
ui = fluidPage(
sliderInput("slider", "Slider", 1, 10, 5),
downloadButton("report", "Generate report")
),
server = function(input, output) {
test1 <- reactive({
n = input$slider
df=matrix(1:n^2,n,n)
df = as.data.frame(df)
result <- list(df=df,n=n)
return(result)
})
output$report <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "report.pdf",
content = function(file) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
params <- list(n = test1()$n,
df = test1()$df)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
And here is my .rmd file :
---
title: "Title"
author: "Name"
date: "`r Sys.Date()`"
output:
pdf_document :
fig_caption: yes
keep_tex: yes
number_sections: yes
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{background}
\backgroundsetup{
scale=1,
color=black,
opacity=0.4,
angle=0,
pages=all,
contents={
\includegraphics[width=\paperwidth,height=\paperheight]{C:/Users/path_to_image/image.jpg}
}
}
params:
n: NA
df: NA
---
```{r}
# The `params` object is available in the document.
params$n
```
A plot of `params$n` random points.
```{r}
plot(rnorm(params$n), rnorm(params$n))
```
```{r}
params$df %>%
mutate_if(is.numeric, function(x) {
cell_spec(x, "latex", bold = T, color = spec_color(x, end = 0.85),
font_size = spec_font_size(x))
}) %>%
kable("latex", escape = F, booktabs = T, linesep = "", align = "c")%>%
kable_styling(latex_options = c("striped", "scale_down"))
```
The error that I'm getting is :
! Undefined control sequence.
l.171 \centering\rowcolors
{2}{gray!6}{white}
Here is how much of TeX's memory you used:
24161 strings out of 492990
415742 string characters out of 6136334
504502 words of memory out of 5000000
27291 multiletter control sequences out of 15000+600000
19644 words of font info for 30 fonts, out of 8000000 for 9000
1141 hyphenation exceptions out of 8191
62i,4n,56p,577b,315s stack positions out of 5000i,500n,10000p,200000b,80000s
[1]: http
Which in tex community they referring to forgetting something like \end{document}. I should mention that if I use the .rmd file alone and replace the last part with :
{r}
library(kableExtra)
library(dplyr)
iris[1:10, ] %>%
mutate_if(is.numeric, function(x) {
cell_spec(x, "latex", bold = T, color = spec_color(x, end = 0.9),
font_size = spec_font_size(x))
}) %>%
mutate(Species = cell_spec(
Species, "latex", color = "white", bold = T,
background = spec_color(1:10, end = 0.9, option = "A", direction = -1)
)) %>%
kable("latex", escape = F, booktabs = T, linesep = "", align = "c")
I will be able to compile it with that background image, the current shiny app is also generating the report if I exclude the part that related to the background image setting.
That's because xcolor must be loaded before background. Do:
---
title: "Title"
author: "Name"
date: "`r Sys.Date()`"
output:
pdf_document :
fig_caption: yes
keep_tex: yes
number_sections: yes
header-includes:
\usepackage{background}
\usepackage{float}
\backgroundsetup{
scale=1,
color=black,
opacity=0.4,
angle=0,
pages=all,
contents={
\includegraphics[width=\paperwidth,height=\paperheight]{C:/Users/path_to_image/image.jpg}
}
}
---
Note that your "header-includes" is useless because all these packages are automatically included.
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.