I yaml

1 yaml Setup

yaml metadata determines the output file format, looking, and any other additional customizing features of Rmarkdown files.

1.1 HTML Document

title: "R Markdown Features"
subtitle: "A Compact Reference"
author: "[Yongfu Liao](https://liao961120.github.io/)"
date: "`r format(Sys.Date(), '%B %e, %Y')`" 
#bibliography: ref.bib
#csl: apa.csl
link-citations: yes
output:
  bookdown::html_document2:
    css: style.css
    code_folding: show
    df_print: kable
    toc: yes
    toc_depth: 2
    toc_float:
      collapsed: yes

1.2 PDF Document

title: "A PDF document YAML Frontmatter"
author: "廖永賦\\thanks{組別:3 ~~ 系級:心理三 ~~ 學號:B00000000}"
date: "`r format(Sys.Date(), '%B %e, %Y')`"
#bibliography: ref.bib
#csl: apa.csl
documentclass: article
urlcolor: "blue"
fontsize: 12pt 
geometry: a4paper, headheight=0pt, margin=0.4in
linestretch: 1.35
links-as-notes: true
output:
  bookdown::pdf_document2:
    latex_engine: xelatex
    number_sections: no
    toc: no
    includes:
      in_header: header.tex

This is the yaml header for bookdown::pdf_document2 output. Using bookdown extensions have several advantages. Search ‘bookdown’ for details.

You may need to attatch an additional header.tex and set latex_engine to xelatex for PDF documents containing multibite characters (e.g. Chinese). Read more about header.txt.

Note that Latex only accepts fontsize of 10pt, 11pt, or 12pt. See this for more detail.

1.3 PDF: header.tex

The code below is for generating PDF documents written in (Traditional) Chinese.

%加這個就可以設定字體
\usepackage{fontspec}
%使用xeCJK,其他的還有CJK或是xCJK
\usepackage{xeCJK}
%使用 LaTeX bm{boldmath}
% \usepackage{bm}
%圖片處理
\usepackage{float}

% 設定字體大小, 更改 fontsize 的數字
\usepackage[fontsize=12pt]{scrextend}

%設定段落之間的距離
\setlength{\parskip}{0.35cm}

% 設定英文字體
%\setmainfont[Path=fonts/,
% BoldFont={LiberationSerif-Bold.ttf}, 
% ItalicFont={LiberationSerif-Italic.ttf},
% BoldItalicFont={LiberationSerif-BoldItalic.ttf}]{LiberationSerif.ttf}

%設定中文字型
%字型的設定「必須」使用系統內的字型,或 `fonts/` 內的字體
% AR PL KaitiM Big5, 標楷體, .PingFang TC, Noto Sans CJK TC, HanWangHeiLight, HanWangHeiHeavy
% 粗體字型: BoldFont
\setCJKmainfont[AutoFakeBold=1.5,AutoFakeSlant=.4]{AR PL KaitiM Big5}
\setCJKmonofont[AutoFakeBold=1.5,AutoFakeSlant=.4]{Noto Sans Mono CJK TC}
%若字體沒有粗體字型,將上面一行註解掉,改用下方這行
%\setCJKmainfont[AutoFakeBold=1.5,AutoFakeSlant=.4]{AR PL KaitiM Big5}

% 將英文標題翻譯為中文標題
\renewcommand{\figurename}{圖}
\renewcommand{\tablename}{表}
\renewcommand{\contentsname}{目錄}
\renewcommand{\listfigurename}{圖目錄}
\renewcommand{\listtablename}{表目錄}
\renewcommand{\appendixname}{附錄}
\renewcommand{\abstractname}{摘要}


% 如果你不懂 LaTeX,不用理會下方的指令

%中文自動換行
\XeTeXlinebreaklocale "zh"

%文字的彈性間距
\XeTeXlinebreakskip = 0pt plus 1pt

% deal with nuts floating figures
\renewcommand{\textfraction}{0.05}
\renewcommand{\topfraction}{0.8}
\renewcommand{\bottomfraction}{0.8}
\renewcommand{\floatpagefraction}{0.75}


%無編碼之 footer
%使用: \blfootnote{此段文字顯示於 footer region 內}
%見 https://bit.ly/2OI15vo (原始碼) 與 https://bit.ly/2YPkaR9 (輸出) 
\makeatletter
\def\blfootnote{\xdef\@thefnmark{}\@footnotetext}
\makeatother

1.4 PDF: template

output:
  pdf_document:
    template: two-col.latex
    includes:
      in_header: header.tex

It is possible to define custom latex template. For example, two-col.latex is created by putting the variable body (which is the rendered content of the Rmd file) inside multicols latex extension:

\begin{multicols}{2}
$body$
\end{multicols}

1.5 Bibliography

bibliography: ./citation/neanderthals.bib
csl: ./citation/apa.csl # APA style sheet
link-citations: yes

For citation syntax, read the section Bibliography & Citations.

II knitr

2 knitr Parameters

2.1 Root

knitr::opts_knit$set(root.dir='..')

The root directory of the .rmd file you want to knit is set to the directory where the .rmd file is located by default. In the case above, I changed it to the directory that is parent to the default directory. This is useful if you build websites with R Markdown Websites, since R Markdown Websites doesn’t allow hierarchical website structure. By changing the root directory, you can more easly organize your project directory structure without violating the requirement of R Markdown Websites. This is especially true when you source a lot of Rscripts in the .Rmd files.

2.2 Code Chunk & Figure Options

library(svglite) 
knitr::opts_chunk$set(
    echo = FALSE, # No display code chunks
    message = FALSE,
    warning = FALSE,
    dev='svg', # or 'svglite' for multibite characters
    comment="",
    fig.dim = c(3.5, 3.5)  # (width, height)
)
options(digits = 2) # auto round to 2 decimals when printed

3 Child Documents

It is possible to write R Markdown in separated files and combine them together before knitting to the output file. See knitr documentation for more info.

3.1 Usage

main.Rmd:

---
title: "This is Title"
author: "Yongfu Liao"
output: html_document
---

```{r setup}
options(knitr.duplicate.label = 'allow')
```

```{r child="part1.Rmd"}
```

```{r child="part2.Rmd"}
```

The skeleton file that combines several R Markdown files. Only this file is rendered, other R Markdown files will automatically be inserted in the knitting process.

To avoid code chunks having the same labels, set the option below in setup code chunk of main.Rmd.

options(knitr.duplicate.label = 'allow')

4 Conditional Compilation

if (knitr::is_html_output()) {
  ...
}

if (knitr::opts_knit$get('rmarkdown.pandoc.to') == "latex") {
  ...
}

5 Dynamic Variables

Include R Code Chunk Variables in the body of text. This can be a really useful feature for writing thesis or research paper:

  • No need to copy & paste the outcomes, such as the statistics. This greatly reduce the risk of error, and it also largely boosts efficiency.

  • Automatically updates the results in the paper when the data are updated. This also boosts efficiency and, more importantly, increases the reproducibility of the research: you can be confident that the results come directly from the data (unless there are errors in the code, which can be ‘seen’, whereas errors from copy-&-paste’s are invisible).

Below is a simple demonstration of this feature.

tr1 <- rnorm(n=25, mean=1.1) #data of treatment1
tr2 <- rnorm(n=25, mean=0.9) #data of treatment2
ttest <- t.test(tr1, tr2, paired = T)
diff <- ttest[["estimate"]][["mean of the differences"]]
p_val <- ttest[["p.value"]]
  1. The mean difference between the two groups is -0.134.

    The mean difference between the two treatments is `r round(diff, 3)`.
  2. The p-value of the paired t-test is 0.7101, which is not significant.

        The *p*-value of the paired t-test is `r round(p_val, 4)`, which is `r ifelse(p_val<=0.05, "", "not")` significant.

6 Escaping knitr Special Characters

We may sometimes encounter a situation in which we want to show snippets of R Markdown that have special meaning verbatimly, such as ``r fun()`` or R code chunks.

6.1 Display Inline R Code Chunks Verbatimly

Instead of wrapping the code chunk directly with “`”, use “&#96;” instead:

Use

<code>&#96;r knitr::combine_words(names(iris))&#96;</code>

to show

`r knitr::combine_words(names(iris))`

6.2 Display knitr Code Chunks Verbatimly

knitr code chunks (with forms like ```{r}) will be executed when knitting the Rmd file. In order to show knitr code chunks verbatimly, one has to suppress the execution of the code chunks by adding `r ''` in front of ```{r} and then wrap the whole chunk with four backticks:

````Rmd
`r ''````{r}
Some R Code
```
````

The code `r ''` is for suppressing the execution of the r code chunk after it.

7 Bibliographies & Citations

You can read the full documentation of Bibliographies & Citations at Rstudio.

7.1 Citation syntax

Classical Citation: Author, year, and brackets

  • Some text [@citekey].
    • Some text (Abadia & Gonzalez Morales, 2010).

In-text Citation: Author (year)

  • @citekey Some text
    • Csikszentmihalyi (2014) Some text
  • @citekey [p. 20] Some text.
    • Abadia & Gonzalez Morales (2010, p. 20) Some text.

Year only: Suppress Author

  • Some text [-@citekey].

Two Citations

  • Some text [@citekey1; @citekey2].
    • Some text (Abadia & Gonzalez Morales, 2010; Csikszentmihalyi, 2014).
  • Prefix & Suffix
    • Text [see @citekey1 pp.45; also, @citekey2 ch. 2].
    • Text (see Abadia & Gonzalez Morales, 2010, p. 45; also, Csikszentmihalyi, 2014 ch. 2).

7.2 Include .bib file in Reference

Rmarkdown requires specific formats of bibliographies. One of the most common one is .bib. A lot of people (including me) use Endnote to manage bibliographies. Read this to see how to generate .bib files from EndNote.

However, you can’t control the format of the citation key generated by Endnote. Having a well-structured format of citation key greatly enhance efficiency, which can be done by using Zotero and its extension Better BibTeX. I strongly recommend using this approach, since the learning curve isn’t steep and it only hurts once. The payoff is a long-term efficiency boost.

Below are some syntax in Rmarkdown to control the display of reference in the document.

Reference heading

The body of cited reference in the .bib file will be shown under the header named Reference (it doesn’t matter which level of heading you use).

## Reference

Specific Refs

Include specific references that were not cited in the body of text.

---
nocite: |
  @item1, @item2
...

All Refs

Include All references in the body of text.

---
nocite: |
  @*
...

8 Emphasis

An Example

```{block2, type="success"}
| This is line 1, pragraph one. [**Red text**]{.red}. Text text text text.
| This is [line 2]{style="color:rgba(255, 0, 0, 1)"} of paragraph one. 

Paragraph two starts here.
```
This is line 1, pragraph one. Red text. Text text text text.
This is line 2 of paragraph one.
Paragraph two starts here.

Colored divs

Bootstrap Alert

You can use bootstrap’s default alert divs in Rmarkdown, defined with four classes:

  1. alert alert-success
  2. alert alert-warning
  3. alert alert-info
  4. alert alert-danger
```{block, type="alert alert-success"}
Bootstrap-defined colored region
```

Bootstrap-defined colored region

Customized divs

Alternative, you can define your own styled divs, as in my stylesheet1:

There are 4 choices of classes,

  1. success
  2. warning
  3. info
  4. error
```{block, type="info"}
some text in the colored region
```

some text in the colored region

Bootstrap Callouts

Althougt it’s “Bootstrap” callouts, it’s not contained in default bootstrap theme. I defined it in my stylesheet.

There are 4 choices of classes,

  1. bs-callout bs-callout-success
  2. bs-callout bs-callout-warning
  3. bs-callout bs-callout-info
  4. bs-callout bs-callout-error
```{block2, type="bs-callout bs-callout-warning"}
### Heading in Callout
**Calleout Text** texttexttexttexttexttext
```

Heading in Callout

Calleout Text texttexttexttexttexttext

New Line

| Text of line 1
| Text of line 2

New paragraph
Text of line 1
Text of line 2
New paragraph

Attach Attributes

By using [text], pandoc turns the text in the square brackets into the HTML <span> tag. HTML class, id, attributes specific to <span> can then be attached by using the curly braces.

class

Rmarkdown syntax allows attaching attributes (such as class, id, etc.) to certain elements by wrapping attributes into { ... }.

Elements allowed attributes to be attach (by markdown syntax directly):

  1. Section: Attributes are added next to any level of heading.
  2. Link: [Text](LINK){attributes}
  3. span: Text wrapped in [, ]. e.g [Text with class "red"]{.red}.
[**Red Bold text**]{.red}
Red Bold text

Note2.

Other Attributes

Add color through [span style]{style="color:rgba(255, 0, 0, 1)"}
Add color through span style

9 Footnotes with Paragraphs

Check Pandoc for details.

[^longnote]: Here's one with multiple blocks.

    Subsequent paragraphs are indented to show that they belong to the previous footnote. (JUST IGNORE ME, I AM Exteeeeeendiiiiiiing the text to show the effect of paragraph).

    In this way, multi-paragraph footnotes work like multi-paragraph list items.
  • Read the output by clicking the superscript3.

10 Shaped Images (HTML)

Rounded Edge

![](../../local_depend/icons/libreoffice.ico){width=auto height="30%" .rounded}

Boostrap

![](../../local_depend/icons/libreoffice.ico){width=auto height="30%" .img-rounded}
Bootstrap Rounded

Bootstrap Rounded

Circle Image

![](../../local_depend/icons/libreoffice.ico){width=auto height="30%" .circle}
This is figure Caption

This is figure Caption

Boostrap

![](../../local_depend/icons/libreoffice.ico){width=auto height="30%" .img-circle}
Bootstrap Circle

Bootstrap Circle

Thumbnail

![](../../local_depend/icons/libreoffice.ico){width=auto height="30%" .img-thumbnail}
Bootstrap Thumbnail

Bootstrap Thumbnail

11 Figures

11.1 Captions

Include fig.cap='An Caption of the Plot' in the code chunk option gives:

```{r fig.cap='An Caption of the Plot'}
library(ggplot2)
ggplot(iris) +
    geom_point(aes(x = Sepal.Length,
                   y = Sepal.Width,
                   color = Species)
               )
```
An Caption of the Plot

Figure 11.1: An Caption of the Plot

III LaTeX

12 Some \(\LaTeX\) for PDF output

  • \pagenumbering{gobble} This LaTeX code suppress the page number.

  • \pagenumbering{arabic} ‘Turn on’ page number closed by \pagenumbering{gobble}.

  • \newpage: Start a new page

The 3 type of code can be useful in the situation below:

---
title: "A Title"
author: "Someone"
date: "2019-04-08"
---

... Some content in the first page (title page) ...

\pagenumbering{gobble} % Suppress page number on the title page
\newpage               % Start a new page

... Some content in the second page ...

\pagenumbering{arabic} % Revert suppression of page number
                       % Now, the page num starts with '2'

13 \(\LaTeX\) Math

Passing Matrix Object

Setup

Add results='asis' to r code chunk option.

```{r results='asis', echo=FALSE}
library(mat2tex)
mt <- c(1,2)
"$A =" %_% xm(mt,0) %_%"_{2 \\times 1}$"
```

\(A = \begin{pmatrix} 1 \\ 2 \\ \end{pmatrix} _{2 \times 1}\)

Include Matrix in Text

This is the variable `mt`,
```{r results='asis', echo=FALSE}
library(mat2tex)
mt <- matrix(1:4, 2,2)
"$A =" %_% xm(mt,0) %_%"^{-1}$"
```
, which is a matrix.

renders as:

This is the variable mt, \(A = \begin{pmatrix} 1 & 3 \\ 2 & 4 \\ \end{pmatrix} ^{-1}\) , which is a matrix.

Check here for more information.

kable

library(knitr)
library(dplyr)
iris_data <- head(iris) %>%
    select(Sepal.Length, Sepal.Width)

colnames(iris_data) <- c("$\\alpha$", "$\\frac{a}{b}$")
kable(iris_data, format = "markdown", align = "c")
\(\alpha\) \(\frac{a}{b}\)
5.1 3.5
4.9 3.0
4.7 3.2
4.6 3.1
5.0 3.6
5.4 3.9

Plotting Expression

library(latex2exp)
library(ggplot2)
iris_data2 <- iris[c(1:3, 50:53, 100:103), ] %>%
    select(Sepal.Length, Sepal.Width, Species)

iris_data2 %>% ggplot() +
    geom_point(aes(x = Sepal.Length, 
                   y = Sepal.Width, 
                   color = Species)) +
    labs(x = TeX("Length($\\frac{kg}{cm^2}$)"),
         y = TeX("\\frac{a}{b}"))

IV Presentation

14 Xaringan

Xaringan is a HTML presentation output format (based on remark.js) of R Markdown. Xaringan doesn’t support Pandoc markdown, but is very flexible and easy to use if having basic CSS knowledge. It also prints well on PDF (using Chrome or decktape). Read Chapter 7 of R Markdown Guide for more details.

<iframe src=“https://liao961120.github.io/slides/xaringan/index.html”, width=400, height=301>
Slide Link

15 Beamer Slide

Beamer slide is popular among proficient LaTeX users. However, I think Xaringan is a better option since it’s able to print to PDF properly and at the same time having the ability to use interactive HTML features4.

Note: You can use (left & right) arrow keys to navigate through the slides page-by-page.

V Advanced Topics

16 Printing Bookdown to PDF

Although bookdown nicely provides options to render the book to PDF formats, setting up things related to LaTeX can still be demanding, especially for people not familiar with LaTeX. To make bookdown nicely render elements properly to both HTML and PDF also takes some additional efforts. You have to make sure not to use pure HTML or LaTeX commands in Rmd files.

One possible solution is to forget about LaTeX and use HTML compatible syntax entirely. The PDF can then be generated by using the web browser to print the web page. Currently, I found Firefox working better than Chrome in printing nicer appearance of the PDF (e.g., page break before H1 titles).

To achieve this, one has to make all chapters output to one single HTML file and specify some additional CSS styles to tweak the appearance of PDF.

Tweak the appearance of PDF by specifying @media print in style.css5:

@media print {
  div.level1 { 
    page-break-before: always;}
  img {
    display: block;
  }
  img, table, ul, ol, .code-snippet, blockquote, pre {
      page-break-inside: avoid;
  }
}

and include the CSS in _output.yml:

bookdown::gitbook:
  css: style.css

Then compile the book with bookdown::render_book(), the option output_options takes a list as input, which overrides the options specified in _output.yml6:

bookdown::render_book(
    "index.Rmd", output_file = 'single.html',
    output_format = "bookdown::gitbook",
    output_options = list(split_by = "none")
    )

References

Abadia, O. M., & Gonzalez Morales, M. R. (2010). Redefining neanderthals and art: An alternative interpretation of the multiple species model for the origin of behavioural modernity. Oxford Journal of Archaeology, 29(3), 229–243. Journal Article. https://doi.org/10.1111/j.1468-0092.2010.00346.x

Csikszentmihalyi, M. (2014). Society, culture, and person: A systems view of creativity. In The systems model of creativity: The collected works of mihaly csikszentmihalyi (pp. 47–61). Book Section, Dordrecht: Springer Netherlands. https://doi.org/10.1007/978-94-017-9085-7_4


  1. Look at my stylesheet for syntax details.

  2. .red is also a self-defined class in my stylesheet.

  3. Here’s one with multiple blocks.

    Subsequent paragraphs are indented to show that they belong to the previous footnote. (JUST IGNORE ME, I AM Exteeeeeendiiiiiiing the text to show the effect of paragraph).

    In this way, multi-paragraph footnotes work like multi-paragraph list items.

  4. An automatic process can be set to render Xaringan slides, print them to PDF, and host HTML and PDF slides on GitHub Pages. See the output webpage and this .travis.yml if you want to implement it.

  5. Note that page-break-before: always doesn’t seem to work in Chrome, and img { page-break-inside: avoid; } doesn’t work on Firefox (so some images get cut into parts), at least on my computer.

  6. For example, one can set

    bookdown::gitbook:
      split_by: chapter

    so that the default output is for reading on the web (separated HTML files are quicker to load).

    For printing, one can override the default by passing output_options(list(split_by = "none")) to bookdown::render_book() to get a single HTML output file.