LaTex fails to compile PDF - pdf

Since yesterday, I get a confusing error, when trying to knit my Markdown files to PDF. I get this warning:
This is pdfTeX, Version 3.141592653-2.6-1.40.24 (TeX Live 2022) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
I was unable to find any missing LaTeX packages from the error log Chapter-5-1.log.
! Extra }, or forgotten \endgroup.
\endwraptable ...kip \egroup \box \z# \fi \egroup
\WF#floatstyhook \def \wid...
l.156 \end{wraptable}
Fehler: LaTeX failed to compile Chapter-5-1.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See Chapter-5-1.log for more info.
Ausführung angehalten
The problem seems to be the kable tables, which have been knit in prior tries just nicely. In the error log, this is printed:
Overfull \hbox (165.80571pt too wide) in paragraph at lines 142--158
[][]
[]
! Extra }, or forgotten \endgroup.
\endwraptable ...kip \egroup \box \z# \fi \egroup
\WF#floatstyhook \def \wid...
l.158 \end{wraptable}
A friend of mine tried to compile the tex file directly to PDF, but got the same error. We where not able to find a missing } or any other error in the coding. All tables and code is running without error in the markdown preview.
I get the same error, when I try to knit a document with a dummy table, so I hope that works as a reproducible example.
---
title: "Chapter 5"
author: "Moiken Hinrichs"
date: "`r format(Sys.time(), '%d.%m.%Y')`"
header-includes:
- \usepackage{caption}
- \usepackage{float}
- \captionsetup[figure]{font=footnotesize}
- \usepackage{subfig}
- \usepackage{flafter}
- \usepackage{footmisc}
output:
bookdown::pdf_document2:
extra_dependencies: ["flafter"]
number_sections: true
toc: false
latex_engine: xelatex
classoption: twoside
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(dplyr, quietly=T)
library(tidyr)
```
```{r prox}
column1 <- c("Bert", "Angela", "Nico", "Pam", "Max")
column2 <- c(33, 54, 85, 96, 57)
prox <- data.frame(column1, column2)
prox[nrow(prox)+1, ] <- c('Total', sum(prox$column2))
kable(prox, booktabs = T, linesep = "",
col.names = c("Name", "Count"),
caption = "Number of items") %>%
kable_styling(latex_options = "striped", position = "float_right") %>%
row_spec(5, hline_after = T) %>%
row_spec(6, bold = T)
```
R studio and tinytex are updated. I tried all the debugging tips and uninstalled and installed tinytex new. The same error is also happening when I try to knit on another computer. I also tried to change from xelatex to pdflatex but the error was the same.

The wrapfig package does not particular like zero width wrapfigure or -table environments with captions. Unfortunately that's the width rmarkdown seems to use by default.
The package documentation has the following to say about the topic:
[...] However, if you specify a width of zero (0pt), the actual width of the figure will determine the wrapping width. A following \caption should have the same width as the figure, but it might fail badly; it is safer to specify a width when you use a caption.
You can avoid the problem by choosing a suitable width:
---
title: "Chapter 5"
author: "Moiken Hinrichs"
date: "`r format(Sys.time(), '%d.%m.%Y')`"
header-includes:
- \usepackage{caption}
- \usepackage{float}
- \captionsetup[figure]{font=footnotesize}
- \usepackage{subfig}
- \usepackage{flafter}
- \usepackage{footmisc}
- \usepackage{lipsum}
output:
bookdown::pdf_document2:
extra_dependencies: ["flafter"]
number_sections: true
toc: false
latex_engine: xelatex
classoption: twoside
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)
library(dplyr, quietly=T)
library(tidyr)
```
```{r prox}
column1 <- c("Bert", "Angela", "Nico", "Pam", "Max")
column2 <- c(33, 54, 85, 96, 57)
prox <- data.frame(column1, column2)
prox[nrow(prox)+1, ] <- c('Total', sum(prox$column2))
kable(prox, booktabs = T, linesep = "",
col.names = c("Name", "Count"),
caption = "Number of items") %>%
kable_styling(latex_options = "striped", position = "float_right", wraptable_width = "3cm") %>%
row_spec(5, hline_after = T) %>%
row_spec(6, bold = T)
```
\lipsum

Related

How can I modify the color of cross-referencing in the R markdown generated pdf document?

---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
extra_dependencies: ["float"]
number_sections: false
toc: false
linkcolor: blue
---
```{r, echo = FALSE}
library(ggplot2)
data(mtcars)
names(mtcars)
```
### Heading 1
```{r figure-1,echo=FALSE, fig.cap = "Sample Graph 1"}
ggplot(mtcars,aes(x=mpg,y=hp))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \textcolor{blue}{\#ref(fig:figure-2)}
\newpage
### Heading 2
```{r figure-2,echo=FALSE, fig.cap = "Sample Graph 2"}
ggplot(mtcars,aes(x=mpg,y=carb))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \#ref(fig:figure-1)
After execution, I found the following in knitted pdf document before Heading 2.
To see another graph, please see figure reffig:figure-2
reffig:figure in the code is not cross-referenced as well. What I want is that my document should show the following line in the pdf document:
To see another graph, please see figure 2
"2" in the above statement should be hyperlinked and its color should be blue, enabling the reader to jump to figure 2 if user clicks on "2".
Adding urlcolor:blue to your yaml should work.
---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
extra_dependencies: ["float"]
number_sections: false
toc: false
linkcolor: blue
urlcolor: blue
---
Original answer found here: R markdown link is not formatted blue when knitted to pdf

! Package pdftex.def Error - when knitting to PDF

I am able to knit to PDF for the example below:
---
title: "R Notebook"
output:
pdf_document: default
html_notebook: default
html_document:
df_print: paged
---
Table 1 example:
```{r, warning=FALSE, message=FALSE, echo=FALSE, include=FALSE, fig.pos="H"}
library(magrittr)
library(tidyverse)
library(kableExtra)
library(readxl)
library(modelsummary)
library(scales)
tmp <- mtcars
# create a list with individual variables
# remove missing and rescale
tmp_list <- lapply(tmp, na.omit)
tmp_list <- lapply(tmp_list, scale)
# create a table with `datasummary`
# add a histogram with column_spec and spec_hist
# add a boxplot with colun_spec and spec_box
emptycol = function(x) " "
final_4_table <- datasummary(mpg + cyl + disp + hp + drat + wt + qsec + vs + am + gear + carb ~ N + Mean + SD + Heading("Boxplot") * emptycol + Heading("Histogram") * emptycol, data = tmp) %>%
column_spec(column = 5, image = spec_boxplot(tmp_list)) %>%
column_spec(column = 6, image = spec_hist(tmp_list))
```
```{r finaltable, echo=FALSE}
final_4_table
```
However, I cannot knit to PDF my own code which involves more variables. My R Markdown starts by reading my excel file and then it is pretty much the same as example above:
---
title: "table1"
output:
pdf_document: default
html_document:
df_print: paged
---
Table 1
```{r prep-tableone, message=FALSE, warning=FALSE, echo=FALSE, include=FALSE, fig.pos="H"}
library(magrittr)
library(tidyverse)
library(kableExtra)
library(readxl)
library(modelsummary)
library(scales)
### set directory
setwd("/etcetc1")
## read dataset
my_dataset <- read_excel("my_dataset.xlsx")
my_dataset <- as.data.frame(my_dataset)
...
I can run this code in R script; it works just fine. I can also knit this code to HTML just fine. When trying to knit to PDF I get the following error:
output file: table1test.knit.md
! Package pdftex.def Error: File `table1test_files/figure-latex//boxplot_65c214bae9bb.pdf' not found: using draft setting.
Error: LaTeX failed to compile table1test.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See table1test.log for more info.
In addition: Warning messages:
1: package 'ggplot2' was built under R version 4.1.1
2: package 'tibble' was built under R version 4.1.1
3: package 'tidyr' was built under R version 4.1.1
4: In in_dir(input_dir(), evaluate(code, envir = env, new_device = FALSE, :
You changed the working directory to /etcetc1 (probably via setwd()). It will be restored to /etcetc2. See the Note section in ?knitr::knit
Execution halted
Am I missing any packages? Do you know what might be happening?
I use TeXShop for LaTeX.

kable unable to output unicode character in pdf_book (bookdown)

I am trying to use the checkmark unicode character (\u2713) in a table rendered by kable in a bookdown project. A MWE consists in the following 2 files (index.Rmd, preamble.tex) part of the generated minimal bookdown project.
index.Rmd
---
title: "A Minimal Book Example"
subtitle: "subtitle"
lang: fr
author: "Yihui Xie"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
mainfont: Arial
mathfont: Arial
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
subparagraph: yes
description: "This is a minimal example of using the bookdown package to write a book. The output format for this example is bookdown::gitbook."
---
```{r setup, include=FALSE}
# Set locale to french for month and day names (calendar plots)
Sys.setlocale(locale = 'French')
# Load all needed libraries
if(!require('pacman'))install.packages('pacman')
pacman::p_load(kableExtra)
```
(ref:O3) O~3~
# Prerequisites
✓
```{r stations-polluants, echo=FALSE}
stations_polluants_table <- data.frame(
stations = c("41B001", "41B004", "41B011", "41MEU1", "41N043", "41R001", "41R002", "41R012", "41WOL1", "Total / polluant"),
O3 = c("", rep("✓", 5), "", rep("\u2713", 2), "7")
)
kable(stations_polluants_table, col.names = c("Station", "(ref:O3)"), booktabs = T, align = "c", caption = "Caption text") %>%
row_spec(0, bold = T) %>%
row_spec(10, bold = T) %>%
collapse_rows(columns = 1, latex_hline = "major", valign = "top")
```
```{r include=FALSE}
# automatically create a bib database for R packages
knitr::write_bib(c(
.packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')
```
preamble.tex
\usepackage{booktabs}
\newfontfamily{\unicodefont}{Arial Unicode MS}
\usepackage{newunicodechar}
\newunicodechar{✓}{{\unicodefont{✓}}}
By compiling in PDF with rmarkdown::render_site(output_format = 'bookdown::pdf_book', encoding = 'UTF-8') one can notice that ✓ is correctly rendered in the text, while it is replaced by <U+2713> in the generated table. I also tried to use \u2713 in the table without more success.
What am I doing wrong ? Please note that, even if the prefered output is PDF, I would also like to compile as gitbook (so Rmd files need to stay independent from the output format).
Many thanks.
After having a moment of clarity, the solution simply lies in using text references in bookdown, i.e. (ref:check) ✓ and use the reference within the table.
index.Rmd
```{r setup, include=FALSE}
# Set locale to french for month and day names (calendar plots)
Sys.setlocale(locale = 'French')
# Load all needed libraries
if(!require('pacman'))install.packages('pacman')
pacman::p_load(kableExtra)
```
(ref:O3) O~3~
# Prerequisites
✓
(ref:check) ✓
```{r stations-polluants, echo=FALSE}
stations_polluants_table <- data.frame(
stations = c("41B001", "41B004", "41B011", "41MEU1", "41N043", "41R001", "41R002", "41R012", "41WOL1", "Total / polluant"),
O3 = c("", rep("(ref:check)", 5), "", rep("(ref:check)", 2), "7")
)
kable(stations_polluants_table, col.names = c("Station", "(ref:O3)"), booktabs = T, align = "c", caption = "Caption text") %>%
row_spec(0, bold = T) %>%
row_spec(10, bold = T) %>%
collapse_rows(columns = 1, latex_hline = "major", valign = "top")
```
```{r include=FALSE}
# automatically create a bib database for R packages
knitr::write_bib(c(
.packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')
```

DT table will not show in Rmarkdown with Word output

I am trying to render a static DT to word.
I have this stripped down version of a file example.Rmd and I am using knitr version 1.30 and the latest stable versions of all relevant packages. Per https://bookdown.org/yihui/bookdown/html-widgets.html the datatable should render but I am not getting the static DT back just the echo=TRUE part.
Please help me if you can - I am hopelessly stuck and I cannot just use another table.
title: 'Main title'
subtitle: 'Subtitle here'
always_allow_html: yes
# params:these will come from SHINY APP
# x1: x1
# x2: x2
# x3 :x3
output:
word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', echo=TRUE, cache=FALSE, warning = TRUE, message = TRUE, tidy=TRUE}
library(DT)
library(webshot)
if(is.null(webshot:::find_phantom())){webshot::install_phantomjs()}
DT::renderDataTable(iris)
```
The solution to this problem is to replace renderDataTable with datatable which allows webshot to kick in.
title: 'Main title'
subtitle: 'Subtitle here'
always_allow_html: yes
# params:these will come from SHINY APP
# x1: x1
# x2: x2
# x3 :x3
output:
word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', echo=TRUE, cache=FALSE, warning = TRUE, message = TRUE, tidy=TRUE}
library(DT)
library(webshot)
if(is.null(webshot:::find_phantom())){webshot::install_phantomjs()}
DT::datatable(iris)
```
Here is what I did, I am not sure if you can render DT into a static table file straight into Word like you are wanting, but maybe I am unaware. The DT is a javascript library so it's suppose to be dynamic and user interactive in a web browser. but the knitr::kable() function will render your table entirely straight into word.
---
title: 'Main title'
subtitle: 'Subtitle here'
always_allow_html: yes
runtime: shiny
output:
html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', cache=FALSE, warning = FALSE, message = FALSE}
library(DT)
library(webshot)
if(is.null(webshot:::find_phantom())){webshot::install_phantomjs()}
DT::renderDataTable(iris)
```
Maybe use just a simple table output with knitr::kable, which will render your entire table straight to a word doc from Rmarkdown.
---
title: 'Main title'
subtitle: 'Subtitle here'
output:
word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
```{r, fig.align='center', cache=FALSE, warning = FALSE, message = FALSE}
library(DT)
library(knitr)
knitr::kable(iris)
```

Flexdashboard not able to render ggplotly and ggplot object on same markdown

I have a basic reproducible example here that I think might just be a package limitation. I was wondering if I am just doing something wrong? They both plot fine separately but when combined in the same markdown make the dashboard unable to correctly render.
---
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: rows
source_code: embed
runtime: shiny
---
```{r setup, include=FALSE}
library(tidyverse)
library(plotly)
library(albersusa)
state_sf <- usa_sf("aeqd")
state_dat <- data.frame(state = c("Washington", "Wyoming","Texas","California"), pct = c(0.3,0.5,0.8,0.1))
state_map <- state_sf %>%
left_join(state_dat, by = c("name" = "state"))
```
Test
=====================================
Sidebar {.sidebar data-width=200}
-------------------------------------
Testing
Row
-----------------------------------------------------------------------
###Plotly
```{r graph 1, fig.height=4, fig.width=6}
#Symptoms by state last week===================================================
ggplotly(
ggplot(data = state_map) +
geom_sf(aes(fill=pct))
)
```
###Bar
```{r graph 2, fig.height=4, fig.width=3}
ggplot(data=state_dat) +
geom_col(aes(state,pct,fill=pct))
```
If you are using runtime: shiny you need to use the proper type of Shiny's renderX() functions for each type of plot object to display properly. I don't know why only one plot chunk (w/o renderX()) works, but two breaks it.
### Plotly
```{r graph_1, fig.height=4, fig.width=3}
#Symptoms by state last week
renderPlotly({
ggplotly(
ggplot(data = state_map) +
geom_sf(aes(fill=pct))
)
})
```
### Bar
```{r graph_2, fig.height=4, fig.width=3}
renderPlot({
ggplot(data=state_dat) +
geom_col(aes(state,pct,fill=pct))
})
```