Bookdown / Knitr / Kable Outputting Perfectly to HTML but No Table to PDF - r-markdown

I am using the bookdown package to produce a large document with tables using the knitr::kable function. I can get the document to produce tables in HTML perfectly, but in PDF, the table contents just appear as a list of numbers. This is also true for the output to Word. The compiled LaTeX just appears to be a list of numbers as well.
This is also true of output from other packages like sjplot.
The same problem also appears when the sample code from the bookdown book.
knitr::kable(
list(
head(iris[, 1:2], 3),
head(mtcars[, 1:3], 5)
),
caption = 'A Tale of Two Tables.', booktabs = TRUE
)
Produces the expected output in HTML:
But, produces the following in PDF:
The YAML header in index.rmd are:
#output ~~~~~~~~~~~ [see _output.yml]
site: bookdown::bookdown_site
output: [bookdown::gitbook, bookdown::pdf_book, bookdown::word_document2, bookdown::html_document2]
documentclass: book
The output settings in the _output.yml are:
bookdown::pdf_book:
keep_tex: true
latex_engine: xelatex
includes:
in_header: tex/biblio.tex
number_sections: yes
pandoc_args: ["--top-level-division=chapter"]

It turns out the problem arises from some interaction with the kableExtra package
So, even if you specify (as I did in my sample code) the knitr namespace (knitr::kable), there is still some downstream interference if kableExtra is loaded. So, this will not work when rendering to PDF:
library(kableExtra, warn.conflicts = TRUE)
knitr::kable(head(iris, 20), caption = 'Here is a nice table!', booktabs = TRUE)
While everything works for the HTML output, the rendering to PDF does not work for the tables and you just end up with a list of the table cell values (for both PDF and Word) - as shown in the image above.
To solve, remove any library statements
Then, ensure you unload the package:
detach("package:kableExtra", unload = TRUE)
And, finally, for me, I found that I needed to "Restart R and Clear All Outputs" or "Terminate R" from the R-Studio "Session" menu.

Related

How do I automatically number images in html using R Markdown?

I am using R Markdown to create a long html document with multiple images inserted throughout. I need automatically numbered figure captions, but cannot figure out how to generate them.
I insert figures this way:
![An informative figure caption](path.png)
The YAML metadata looks like this:
title: "My Title"
author: "me"
bibliography: References.bibtex
output:
bookdown::html_document2:
number_sections: TRUE
fig_caption: TRUE

Issues with different citation packages in bookdown

I am creating a pdf-book using bookdown, with a .bib file that holds my citations. I call the citations with the standard [#citation] used in bookdown. Citing works correctly, but the bibliography doesn't seem to be how I wanted it.
Here are the things that I need to work:
The bibliography should be included in the toc, at the end of \mainmatter, but before the \backmatter, which I use to attach pdf's as an appendix, where the appendix header is listed in the toc
The in-text citations should be in number format, with possible nested citations, like this: [1,2]
Bibliography should be in the order they appear in the text, with the possibility of removing DOI/URLs etc as I see fit
For these things to work so far, I've tried the natbib package, which seem to work fine. However, I do not seem to be able to remove DOI/URLs from specific bibliography entries, such as journal articles. Therefore, I tried using biblatex or the built-in pandoc, but neither seem to work properly (With pandoc the bibliography is gone from the toc, and the bibliography entries are messy. With biblatex, i get multiple errors that the program can't find specific entries in the .bib file, which are there)
This is my YAML with natbib:
site: bookdown::bookdown_site
geometry: "left=4cm,right=3cm,top=3cm,bottom=3cm"
subparagraph: true
output:
bookdown::pdf_book:
latex_engine: xelatex
fig_caption: yes
toc: false
citation_package: natbib
includes:
before_body: frontpage.tex
after_body: after_body.tex
in_header: preamble.tex
fontsize: 11pt
linestretch: 1.2
documentclass: book
bibliography: [packages.bib, libraryzotero.bib]
link-citations: yes
---
And this is in my preamble.tex:
\usepackage{titlesec}
\usepackage{pdfpages}
\titleformat{\chapter}
{\normalfont\LARGE\bfseries}{\thechapter}{1em}{} % set title format
\titlespacing*{\chapter}{0pt}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}
\AtBeginDocument{\let\maketitle\relax}
\usepackage{makeidx}
\makeindex
\setcitestyle{numbers,square,comma}
\usepackage{url}
\usepackage[nottoc]{tocbibind}
\usepackage{caption}
\captionsetup[figure]{textfont={small,it}, labelfont={normalsize,bf,it}} % set figure caption font size and style
\usepackage{graphicx}
\usepackage{float}
\let\origfigure\figure
\let\endorigfigure\endfigure
\renewenvironment{figure}[1][2] {
\expandafter\origfigure\expandafter[H]
} {
\endorigfigure
}
\raggedbottom
\usepackage{fancyhdr,blindtext}
\fancyhf{}
\fancyhead[LO]{\slshape \rightmark} %section
\fancyhead[RO]{\thepage}
\fancyhead[RE]{\slshape \leftmark} % chapter
\fancyhead[LE]{\thepage}
\setlength{\headheight}{27.7pt} % as requested by fancyhdr's warning
\renewcommand{\sectionmark}[1]{\markright{\thesection.\ #1}}
\makeatletter
\renewcommand{\chaptermark}[1]{% % change settings for including headers
\if#mainmatter
\markboth{Chapter \thechapter{}: #1}{}%
\else
\markboth{#1}{}%
\fi
}
\makeatother
\usepackage{epigraph}
\setcounter{secnumdepth}{1}
\setcounter{tocdepth}{1}
Where \setcitestyle{numbers, square, comma} is for the in-text references.
Does anyone have any suggestions how to get these things to work with bookdown?
For the natbib based solution you could patch the used bibliography style:
You are not setting any bibliography style. Therefore plainnat.bst is used.
Copy plainnat.bst from your TeX installation (typically TEXMF/bibtex/bst/natbib/) to your working directory with a new name.
Add biblio-style: <new-name> to your YAML header.
Edit your BST file:
Find FUNCTION {article}.
Within that block remove format.doi output and format.url output.
Repeat for other types.

Ordering of code chunk outputs in Rmd/HTML reports

I have a summary figure that I want to insert at the top of my HTML report generated using knitr/rmarkdown. But the inputs of this figure depend on outputs generated from downstream code chunks and child documents. Is there a way to do this without having to put the summary figure at the end of the document?
I have tried ref.label='last' option in the top level code chunk (with eval=FALSE) to add a duplicate code chunk in the end of the document {r last, eval=TRUE}, but has not worked for me.
Any suggestions?
You can insert HTML anywhere into your document referencing the figure by the name knitr will use for it.
To figure out the name, temporarily change the YAML header to something like this:
output:
html_document:
self_contained: FALSE
This won't embed figures in the output, they'll be kept in a separate directory. Open the output in an editor, or view source in a browser, and look for the line that displays the figure. In my test example below, it was being displayed by this code:
<p><img src="Untitled2_files/figure-html/rnormplot-1.png" width="672" /></p>
I copied that line into the document, and removed the self_contained setting, and got this source code:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
This is the figure before it was generated:
<p><img src="Untitled2_files/figure-html/rnormplot-1.png" width="672" /></p>
And here it is being generated:
```{r rnormplot}
x <- rnorm(100)
plot(x)
```
One key is to name the code chunk that generates the plot (mine is named rnormplot) because that helps to make sure the figure name is independent of the rest of the document.

R Markdown - HTML Output in Powerpoint

I try to get Highouts Output in my Powerpoint presentation, but the suggestion does not work .This feature is still pretty new and I was not able to find something valueable in the docu.
---
title: "Untitled"
output:
beamer_presentation: default
powerpoint_presentation: default
ioslides_presentation: default
always_allow_html: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(highcharter)
```
### R Markdown
This is an R Markdown presentation. Markdown is a simple formatting
syntax for authoring HTML, PDF, and MS Word documents. For more
details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that
includes both content as well as the output of any embedded R code
chunks within the document.
### Slide with Bullets
- Bullet 1
- Bullet 2
- Bullet 3
### Slide with R Output
```{r cars, echo = TRUE}
highchart() %>%
hc_add_series(data = mtcars, type = "bar", hcaes(y = cyl))
```
### Slide with Plot
```{r pressure}
plot(pressure)
```
Produces:
Functions that produce HTML output found in document targeting pptx output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:
always_allow_html: yes
Note however that the HTML output will not be visible in non-HTML formats.
I added the always_allow_html: yes part to the top, but it still does not work. Can anyone help me?

Self-contained rmarkdown file contains only some embedded images

I'm seeing different behaviour in an R Markdown (Rmd) file depending on how I reference the image I'd like to embed in an HTML document. In the simple example below, the second image is embedded in the document, but the first (using the R chunk) is not.
---
title: "title"
output:
html_document:
mode: selfcontained
theme: null
---
```{r packages, echo=FALSE}
library(htmltools)
```
```{r imgTest, echo=FALSE}
img(src = "http://placehold.it/350x150")
```
<img src="http://placehold.it/350x150">
This is the output in the HTML (for the relevant bit):
<p><img src="http://placehold.it/350x150"/></p>
<p><img src="data:image/png;base64,iVBORw0KG<SNIPPED>"></p>
In summary, using the htmltools function img() within a code chunk does not embed the image but instead it remains a link.
For various reasons, I need the document to be truly self-contained (no links) and to also avoid raw HTML.
Can anyone explain why this is happening and offer a solution? I've tried a variety of chunk options without success so far.