Cross-referencing in RMarkdown redoc documents - r-markdown

I want to create a report using RMarkdown and the redoc package with figures, images and equations but I couldn't figure out how to cross-reference them within the text.
My attempt so far was using the bookdown syntax:
---
title: "Test"
output:
redoc::redoc
---
```{r setup}
library(redoc)
```
This does not work: Figure \#ref(fig:pressure)
```{r pressure, fig.cap="Pressure"}
plot(pressure)
```
And this does also not work: Equation \#ref(eq:binom)
\begin{equation}
1+1=2
(\#eq:binom)
\end{equation}
Is there any workaround for redoc?

Related

How to create own table in Bookdown and reference it within the text?

I am currently writing my thesis in RMarkdown using the template Oxforddown (which is ultimately based on bookdown). I have been reading the documentation but I confess I am lost. I am trying to create a table that contains an overview of the experimental conditions and items I used in my empirical study, so it is not data that I can load into R and then use the kable function on. However, I do not understand how I could generate such a table. Generating RMarkdown tables outside code chunks seems to work, but then the captions and referencing are very different than the rest of the captions used so far, which I usually set up within code chunks. Example below:
{r pilot-short7, echo=FALSE, fig.scap="Pilot 2: ....", out.width="65%", message=FALSE, fig.pos='H', fig.align = 'center'}
When I am trying to include RMarkdown tables inside a code chunks, things go wrong. What would my options be?
Any help would be very much appreciated!
I prepared a markdown template for you.
Here I made a table with flextable library.
But you can use another, which you like, f.e.: kableExtra, gt etc.
As you can see, you should put \label{tab:caption} and after refer in the text by \ref{tab:caption}.
---
title: "Hello World"
header-includes:
- \usepackage{caption}
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, include = FALSE}
library(flextable)
library(dplyr)
table2 <- flextable(mtcars[1:5, 1:6])
```
This is an R Markdown document. 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. You can embed an R code chunk like this:
\begin{table}[hbtp]
\captionof{table}{Text of the caption.}
\label{tab:caption}
`r table2`
\end{table}
Table \ref{tab:caption} is the baddest table in the World

Adding a letter to all table numbers in RMarkdown

I'm using RMarkdown to create Supplementary documents for a paper. These supplements contain many tables. Let's call these documents Supplement A and Supplement B. I want the table numbering to reflect the supplement letter, that is, Table A1 or Table 1A for the first table in Supplement A and so on for all tables.
How can I modify the table numbering to add a letter into the table numbering schema?
Here's an example that will produce a table with normal numbering:
---
title: "Supplement A"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
```
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="MTCars") %>%
kable_styling(latex_options="hold_position", position="left")
```
An inelegant solution using the captioner package (details provided here: https://datascienceplus.com/r-markdown-how-to-number-and-reference-tables/) can create captions and insert them manually just before the code chunk. Combining this with the Latex package caption makes it possible to remove the automatic table naming and numbering if the caption is generated within the code chunk (How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?). I've done this in the YAML with \captionsetup[table]{labelformat=empty}, but it can be done in the document body also. Either way, the caption can then be generated within the code chunk, which was important in my case.
This solution stops bookdown referencing from working (because labelformat cannot be empty), but a workaround for table referencing was provided in the link for using the captioner package (and is included below).
---
title: "Supplement A"
header-includes:
- \usepackage{caption}
\captionsetup[table]{labelformat=empty}
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(captioner)
library(stringr)
```
```{r captions}
# Create the caption(s)
caption <- captioner("Table A", FALSE)
tab_1_cap <- caption("Tab_1", "MTCars")
# Create a function for referring to the tables in text
ref <- function(x) str_extract(x, "[^:]*")
```
The following table is `r ref(tab_1_cap)`.
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption=tab_1_cap) %>%
kable_styling(latex_options="hold_position", position="left")
```
An alternative solution is avaiable via LaTeX. Add the following somewhere in the body of the document to change the default figure and table names to include the letter.
\def\figurename{Figure A}
\def\tablename{Table A}
To reference a table or figure in text use, e.g., Table A\#ref(tab:label), after defining the table label as normal.
This alone will leave a space in the table/figure caption (e.g., 'Table A 1' instead of 'Table A1'). This can be solved by adding the following to the YAML:
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
The \DeclareCaptionLabelFormat creates a function (here labeled nospace), which overrides the default caption label when called. #1 represents the label assigned to refer to tables or figures (e.g., 'Table A') and #2 represents the number of the table or figure. The captionsetup lines change the label format for all tables and figures to the format defined by 'nospace'.
Thus, the code produces, e.g., 'Table A1: Table name' as the caption. If instead you wanted, e.g., 'Table A-1: Table name', the code in \DeclareCaptionLabelFormat should be changed to {#1-#2}.
---
title: "Supplement A"
output: bookdown::pdf_document2
toc: false
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(bookdown)
```
\def\figurename{Figure A}
\def\tablename{Table A}
See Table A\#ref(tab:cars) for something about cars.
(ref:cars) Table caption
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="(ref:cars)") %>%
kable_styling(latex_options="hold_position", position="left")
```
Answer inspired by: Figure name in caption using RMarkdown
Caption latex package documentation: https://ctan.org/pkg/caption

How to embed highcharter in rmarkdown to share (not a loop)

I cannot get two simple highcharter charts in an Rmarkdown file I want to share. It works fine and renders in my PC or Mac, but when I share the file, people only see text.
They are not part of a loop, as mentioned in few articles. They are just two charts. For the reproducible example, I literally just opened a new rmarkdown doc and selected html. I replaced the "summary table" of cars with highcharter code. I even tried htmltools::tagList(chart1, chart2) and it does not work.
I am supplying the code. If you please show me how to do it with one chart, I can do it with the second.
Thank you.
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))
I apologize if the tick marks hide the code background, but the three chunks are wrapped with the three tickmarks at the beginning and end of each chunk.
Thank you again.
Yes the code below produces the file below the code. I now have an entire .html file that has the highchart self contained in the file.
---
output:
html_document:
self_contained: yes
mode: selfcontained
---
{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))

Automatically Change RMarkdown Text Styles from One to Another

Due to different journal requirements, I need to frequently change certain text styles within Rmarkdown from one kind to another. For instance, here is an example Rmarkdown document.
---
title: "Changing format of Rmarkdown"
author: "Paul Hargarten"
date: "5/9/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an $\mathcal{R}$ Markdown document. Markdown is a simple formatting syntax for authoring **HTML**, **PDF**, and **MS Word* documents. For more details on using $\mathcal{R}$ Markdown see <http://rmarkdown.rstudio.com>. $\matcal{R}$ is based on $\mathcal{S}$.
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. Calculate a `summary` as follows:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example: `r plot(pressure)`.
Without searching for the exact phrase, suppose that I would like to find and replace the following items:
1. Change items in bold ** ... ** to italics _ ... _.
2. Change items that look like $\mathcal{ ... }$ to bold ** ... **.
3. Change special font `...`, except those that start with r, to \code{ ... }.
4. Add dollar signs to `r ... ` => $`r ... `$.
Is this possible to use regex to make these formatting style changes in
Rmarkdown? Thanks!
This is something that LaTeX is good at, but it will be harder with Markdown.
If you were entirely in LaTeX, you could define your own macros based on the uses for that markup. For example,
\newcommand{\booktitle}[1]{\textbf #1}
used for book titles as \booktitle{The Book}. If you wanted to switch book titles to italic, you'd just change that definition.
Doing this in R Markdown is possible, but you wouldn't be able to mark book titles using **. You could do it (you can embed LaTeX in R Markdown), but it's ugly. For example,
---
title: Using LaTeX
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\newcommand{\booktitle}[1]{\textbf{#1}}
This is \booktitle{The Book}.
Once you're doing this, you might as well switch to Sweave-like *.Rnw format, or all the way to LaTeX.

Auto-Numbering of Figure and Table Captions for HTML Output in R Markdown

Is there a way to automatically number the figures in captions when I knit R Markdown document into an HTML format?
What I would like is for my output to be the following:
Figure 1: Here is my caption for this amazing graph.
However, I am currently getting the following:
Here is my caption for this amazing graph.
Here is my MWE:
---
title: "My title"
author: "Me"
output:
html_document:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r table1, fig.cap="Here is my caption for an amazing table."}
head(mtcars, 2)
```
I have read that this issue is resolved with Bookdown but I've read the Definitive Guide to Bookdown, cover to cover, and can't find it.
If you wish to have numbered figures, you will need to use an output format provided by bookdown. These include html_document2, pdf_document2 etc. See here for a more comprehensive list of options.
Changing your document example html_document to bookdown::html_document2 will resolve your problem.
---
title: "My title"
author: "Me"
output:
bookdown::html_document2:
number_sections: TRUE
fig_caption: TRUE
---
```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```
```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```
```{r plot2, fig.cap="Here is my caption for another amazing graph."}
plot(y,x)
```
If you want to label tables created by knitr::kable, you will need to specify the caption within the table call itself
```{r table1}
knitr::kable(mtcars[1:5, 1:5], caption = "Here is an amazing table")
```