Automatically Change RMarkdown Text Styles from One to Another - r-markdown

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.

Related

Cross-referencing in RMarkdown redoc documents

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?

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

Evaluate a Rmarkdown codechunk only for certain document type (html_document vs pdf_document)

I'd like to add an interactive map (a leaflet) to my HTML document, but this can't be done in a PDF document since they are static.
I know that Rmarkdown can choose to evaluate a chunk depending on a global variable, like this:
```{r setup}
ev_cars = TRUE
```
## First chunk
```{r cars, eval=ev_cars}
summary(cars)
```
I guess my question is "does knitr set a global variable indicating whether it is knitting an html_document or a pdf_document" ?
thanks
knitr::is_latex_output() and knitr::is_html_output do that job.
ref: https://bookdown.org/yihui/rmarkdown-cookbook/latex-html.html

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))

Change Default Beamer slide size

In R markdown when using Beamer slides if you try to plot you need to specify the plot sizes (unlike in the reports) so that the plots fit on a page. This can often result in the plots appearing to be squashed together, as apposed to just a smaller version of the plot.
Is there some method to change the default slide size to alleviate this problem?
I have tried
header-includes:
- \usepackage[papersize={25.6cm,19.2cm}]{geometry}
in the yaml header, and I get the error
! LaTeX Error: Missing \begin{document}.
Using R Markdown I shouldn't need to use this though.
A reproducible example is shown below
---
title: "Plots look bad"
author: "Beavis"
date: "`r format(Sys.time(), '%d/%m/%Y')`"
output: beamer_presentation
header-includes:
- \usepackage{float}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(results = 'hide')
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(cache=TRUE)
knitr::opts_chunk$set(fig.height=3.5)
```
# Introduction
```{r}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
Here, you if you run this the second slide looks like this As you can see the plot is rubbish. What is the best way to avoid this problem?
The biplot function uses par(pty = "s") to force a square plot, so it's not going to fill a rectangular slide. You can make it look better by asking the fig.height to be bigger, but then it will overflow the bottom of the slide. To prevent this, you can set both fig.height to a large number, and out.height (which will be a LaTeX measurement) to something that will fit on a slide. For example, using this chunk
```{r fig.height=10, out.height="0.8\\textheight"}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
I see this output:
I'd recommend a smaller fig.height, but your preference may be different.
Both fig.height and out.height could be specified using knitr::opts_chunk$set as defaults for all slides if you want.
You could also specify out.width="\\textwidth" for a really ugly stretched plot that fills the slide, but I wouldn't recommend it.