Flextable label not created in rmarkdown - r-markdown

I am using flextable to produce tables for a pdf document rendered with rmarkdwown. I want to cross-reference the tables, but they do not produce the label needed for the cross reference to work.
My Minimum Reproducible Example
What follows is the content of the file test.Rmd:
---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
pdf_document:
fig_caption: yes
includes:
in_header: header.tex
number_sections: yes
toc: yes
toc_depth: 4
latex_engine: xelatex
keep_tex: true
---
```{r, include = FALSE}
library(flextable)
library(bookdown)
opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")
```
```{r, tab.id = "anyTable", tab.cap = "Invented data", tab.lp = "tab:"}
a = data.frame(id = LETTERS[1:3], x = 1:3)
flextable(a) |> theme_vanilla()
```
```{r secondTable}
b = data.frame(id = LETTERS[4:6], x = 4:6)
flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```
# Standard rmarkdown crossreference
Trying anyTable: \ref{tab:anyTable}.
Trying secondTable: \ref{tab:secondTable}.
# Bookdown crossreference
Trying anyTable: \#ref(tab:anyTable).
Trying secondTable: \#ref(tab:secondTable).
Contents of header.tex:
\usepackage{caption}
\renewcommand{\contentsname}{Contenidos}
\captionsetup[table]{name=Tabla}
\captionsetup[figure]{name=Figura}
%\usepackage{float} #use the 'float' package
%\floatplacement{figure}{H}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{xcolor}
\usepackage{multicol}
\usepackage{pdflscape}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}
When I do rmarkdown::render("test.Rmd", output_file = "test.pdf") the file is rendered in pdf, but the following warning comes out:
Output created: test.pdf
Warning message:
LaTeX Warning: Reference `tab:anyTable' on page 1 undefined on input line 198.
LaTeX Warning: Reference `tab:secondTable' on page 1 undefined on input line 20
0.
LaTeX Warning: There were undefined references.
If I check the .tex file, I can see that the captions are there, but they do not have the labels. The relevant lines of the intermediate test.tex file:
lines 106 to 109
\begin{longtable}[c]{|p{0.75in}|p{0.75in}}
\caption{Invented data
}\\
lines 153 to 156
\begin{longtable}[c]{|p{0.75in}|p{0.75in}}
\caption{This is secondTable
}\\
I expected that the caption line in the tex file was something like \caption{This is secondTable}\label{tab:secondTable}\\
What I've tried
Changing latex engines (lualatex, pdflatex, xelatex).
Editing the tex file (adding the label after the caption), but it fails to convert to dvi with multiple errors (mostly "undefined control sequence")
What am I doing wrong?
How can I cross-reference the tables produced by flextable?
Alternatively, I am open to other packages you may suggest. As some of the headers in my real data are somewhat complex (multi-span headers and the like), I would like to steer away from kable and kableExtra if at all possible.

You need to use a format from bookdown to get cross references, see https://bookdown.org/yihui/rmarkdown-cookbook/cross-ref.html
---
title: "document title"
author: "author here"
date: "2022-01-20"
output:
bookdown::pdf_document2:
fig_caption: yes
number_sections: yes
toc: yes
toc_depth: 4
latex_engine: xelatex
keep_tex: true
---
```{r, include = FALSE}
library(flextable)
library(knitr)
library(bookdown)
opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, out.width = "85%", fig.align = "center")
```
```{r, tab.id = "anyTable", tab.cap = "Invented data"}
a = data.frame(id = LETTERS[1:3], x = 1:3)
flextable(a) |> theme_vanilla()
```
```{r secondTable}
b = data.frame(id = LETTERS[4:6], x = 4:6)
flextable(b) |> theme_vanilla() |> set_caption(caption = "This is secondTable")
```
# Bookdown crossreference
Trying anyTable: \#ref(tab:anyTable).
Trying secondTable: \#ref(tab:secondTable).

Related

adding numbers to code blocks in RMD output

I am trying to add line numbers to code blocks, but it's not working. I'm using the code attr.source='.numberLines' with Pandoc 2.11.4. but the output files omit the code numbers.
I've tried the options referenced in this question and also the documentation from bookdown, but the attr.source='.numberLines' is being ignored and it doesn't show up as an autofill option, like say echo= would.
What I want is something that looks like this (just the number part)
Thanks! I've tried this in two different applications of R studio, and it's not working in either.
An example of the code I'm using:
---
title: "example"
author: "plover"
date: '2022-12-29. Version: `r Sys.Date()`'
output:
html_document:
code_folding: show
highlight: tango
number_sections: false
df_print: kable
theme: flatly
toc: yes
toc_float: yes
toc_depth: '3'
word_document:
toc: no
pdf_document:
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Don't evaluate this code
```{r abc, eval = FALSE }
a <-1+1
b <-2+1
c = a + b
```
Don't evaluate this code, but show me the lines
```{r def, eval = FALSE, attr.source = '.numberLines' }
d <-3+1
e <-4+2
f = d + e
```
Evaluate this code, and show me the lines
```{r ghi, attr.source = '.numberLines' }
g <-3+1
h <-4+2
i = g + h
```
Try this. (Actually did nothing but comment out the yaml option code_folding: show)
---
title: "example"
author: "plover"
date: '2022-12-29. Version: `r Sys.Date()`'
output:
pdf_document:
toc: yes
word_document:
toc: no
html_document:
# code_folding: show
highlight: tango
number_sections: false
df_print: kable
theme: flatly
toc: yes
toc_float: yes
toc_depth: '3'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Don't evaluate this code
```{r abc, eval = FALSE }
a <-1+1
b <-2+1
c = a + b
```
Don't evaluate this code, but show me the lines
```{r def, eval = FALSE, attr.source=".numberLines"}
d <-3+1
e <-4+2
f = d + e
```
Evaluate this code, and show me the lines
```{r ghi, eval=FALSE, attr.source=".numberLines"}
g <-3+1
h <-4+2
i = g + h
```

How to print special Latin characters in Markdown pdfs

I need to knit my Markdown script into a pdf file, but when knitted, the pdf file does not show special Latin characters, such as those used in the International Phonetic Alphabet (IPA).
---
title: "MarkdownIPA"
date: '2022-07-06'
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
`Print IPA`
```{r}
'[aɪ.pʰiː.ɛɪ]'
```
Which rends:
How can I fix this?
You'll need to use a font that supports those glyphs. A (IMHO) rather nice one is Source Sans Pro and the monospace variant Source Code Pro.
To use Source Code Pro, you can add the respective LaTeX code directly:
---
title: "MarkdownIPA"
date: '2022-07-06'
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \usepackage{sourcecodepro}
---
Result:
The sourcecodepro package is likely already installed; otherwise you'd have to install it first.

Setting citation_package option under pdf_document in YAML Header and using rmarkdown::pdf_document function

The help file of the pdf_document function of the Rmarkdown CRAN package says that the function is defined with the following options:
pdf_document(toc = FALSE, toc_depth = 2, number_sections = FALSE,
fig_width = 6.5, fig_height = 4.5, fig_crop = TRUE,
fig_caption = TRUE, dev = "pdf", df_print = "default",
highlight = "default", template = "default", keep_tex = FALSE,
latex_engine = "pdflatex", citation_package = c("none", "natbib",
"biblatex"), includes = NULL, md_extensions = NULL,
pandoc_args = NULL, extra_dependencies = NULL)
I am under the impression that I could add any of these arguments as options under pdf_document in the output section of the YAML header in my Rmarkdown document. Is this correct? The document managed to compile when I used the following options/arguments of pdf_document: toc, number_sections, fig_caption, df_print, and keep_tex. However, when I add citation_package to the list, I get an error in compiling. For instance, consider the following template Rmarkdown document.
---
title: "Untitled"
author: "Unknown"
date: "4/18/2019"
output:
pdf_document:
# toc: true
number_sections: true
fig_caption: true
df_print: kable
keep_tex: true
citation_package: biblatex
bibliography: sample_bib.bib
csl: /Users/Shared/Zotero/styles/multidisciplinary-digital-publishing-institute.csl
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
I love R [#rcoreteamLanguageEnvironmentStatistical2018].
The sample_bib.bib mentioned is the bib file that looks like
#software{rcoreteamLanguageEnvironmentStatistical2018,
location = {{Vienna, Austria}},
title = {R: {{A Language}} and {{Environment}} for {{Statistical Computing}}},
url = {https://www.R-project.org/},
version = {3.5.1},
organization = {{R Foundation for Statistical Computing}},
date = {2018},
author = {{R Core Team}}
}
However, I was unable to knit this Rmarkdown document. I got the following error.
/usr/local/bin/pandoc +RTS -K512m -RTS rmarkdown_pdf_document.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output rmarkdown_pdf_document.tex --template /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rmarkdown/rmd/latex/default-1.17.0.2.tex --number-sections --highlight-style tango --pdf-engine pdflatex --biblatex --variable graphics=yes --variable 'geometry:margin=1in' --variable 'compact-title:yes'
output file: rmarkdown_pdf_document.knit.md
INFO - This is Biber 2.7
INFO - Logfile is 'rmarkdown_pdf_document.blg'
INFO - Reading 'rmarkdown_pdf_document.bcf'
INFO - Found 1 citekeys in bib section 0
INFO - Processing section 0
INFO - Looking for bibtex format file 'sample\_bib.bib' for section 0
ERROR - Cannot find 'sample\_bib.bib'!
INFO - ERRORS: 1
Error: Failed to build the bibliography via biber
Execution halted
Warning message:
LaTeX Warning: Citation 'rcoreteamLanguageEnvironmentStatistical2018' on page 1
undefined on input line 137.
LaTeX Warning: Empty bibliography on input line 169.
Package rerunfilecheck Warning: File `rmarkdown_pdf_document.out' has changed.
(rerunfilecheck) Rerun to get outlines right
(rerunfilecheck) or use package `bookmark'.
LaTeX Warning: There were undefined references.
LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.
Package biblatex Warning: Please (re)run Biber on the file:
(biblatex) rmarkdown_pdf_document
(biblatex) and rerun LaTeX afterwards.
Luckily, this problem is easily fixed by moving the "citation_package" from an option under pdf_document to a separate line in the YAML header. Or:
---
title: "Untitled"
author: "Unknown"
date: "4/18/2019"
output:
pdf_document:
# toc: true
number_sections: true
fig_caption: true
df_print: kable
keep_tex: true
citation_package: biblatex
bibliography: sample_bib.bib
csl: /Users/Shared/Zotero/styles/multidisciplinary-digital-publishing-institute.csl
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
I love R [#rcoreteamLanguageEnvironmentStatistical2018].
Upon knitting this adjusted Rmarkdown document, the result is a pdf_document.
So my question is: Was I right that you could add any of the arguments found in the pdf_document help file on CRAN as options under "pdf_document" in the YAML header in a Rmarkdown file? Or, upon using this particular citation_package argument/option, could this be a possible bug in the rmarkdown::pdf_document() function?
ALSO POSTED ON RMARKDOWN's GITHUB; see for additional comments.

Running code chunk in R-markdown using exam document class

I would like to run a code chunk under a question level in the exam document class, but I keep receiving errors. I am assuming this is because it believes the output from the R-code is Latex code.
---
output: pdf_document
documentclass: exam
header-includes: \usepackage{float}
---
\begin{questions}
\question Answer question...
```{r}
iris%>%
group_by(Species)%>%
summarize(Total=n())
```
\end{questions}
Sometimes \begin{"some environment") ... \end{"some environment") doesn't play well with R chuncks. One work around is to define a new environment.
For example, I defined a file preamble.tex with the following information:
preamble.tex
\usepackage{float}
\newcommand{\bQ}{\begin{questions}}
\newcommand{\eQ}{\end{questions}}
Then, I ran the following.
exam.Rmd
---
documentclass: exam
geometry: margin=.5in
output:
pdf_document:
highlight: haddock
includes:
in_header: preamble.tex
before_body: doc-prefix.tex
after_body: doc-suffix.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\bQ
## Including Plots
\question You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
```{r cars}
summary(cars)
```
\question We can keep the pound signs.
\eQ
Here is the resulting output.
Output
I managed to get something working. It needs some libraries and uses knitr to create the output.
---
output:
pdf_document:
keep_tex: true
documentclass: exam
header-includes: \usepackage{float}
---
```{r setup, include=TRUE,echo=FALSE,message=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(knitr)
```
\begin{questions}
\question Answer question...
```{r, echo=F, comment=NA}
summary = iris %>% group_by(Species) %>% summarize(Total=n())
kable(summary, format='latex')
```
\end{questions}
The problem seems to be the inclusion of # in the output from R for processing by Latex. I avoid this by using kable.

RMarkdown Beamer TOC empty

Using beamer in RMarkdown for presentations, I can't figure out why the TOC is empty. I have tried using a MacBook and Windows.
---
title: "test"
author: "my name"
date: "12/6/2016"
output:
beamer_presentation:
keep_tex: true
toc: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
# Slide 1
Slide content
# Slide 2
Slide content
Outputs the pdf presentation with a title slide, an empty page (where the TOC should be), and then the two slides.
On Windows platform:
> R.version
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 3.1
year 2016
month 06
day 21
svn rev 70800
language R
version.string R version 3.3.1 (2016-06-21)
nickname Bug in Your Hair
RStudio:0.99.896
Rmarkdown: 1.2
knitr: 1.15.1
Somewhat related question here: Table of content in beamer generated with R markdown/knitr
Using the keep_tex: true argument in the YAML, I see from the tex file that the level 1 headers (i.e. # Section) are not being properly converted to sections in the tex file. For example, from the tex file:
\begin{frame}{Slide 1}
Slide content
\end{frame}
It seems that RMarkdown is not making the tex file correctly.
As pointed out here, the TOC will list the sections (as defined by single #'s), and the slide level must be a level below the sections (defined below in the YAML as slide_level: 2 and in the presentation by ##'s). I don't completely understand why you can't have sections at the slide level, but at least this works.
---
title: "test"
author: "my name"
date: "12/6/2016"
output:
beamer_presentation:
keep_tex: true
toc: true
slide_level:2
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
# Section 1
## Slide 1
Slide content
# Section 2
# Slide 2
Slide content