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
    css: style.css
    code_folding: show
    df_print: kable
    toc: yes
    toc_depth: 2
      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
    latex_engine: xelatex
    number_sections: no
    toc: no
      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.

%使用 LaTeX bm{boldmath}
% \usepackage{bm}

% 設定字體大小, 更改 fontsize 的數字


% 設定英文字體
% 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}

% 將英文標題翻譯為中文標題

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

\XeTeXlinebreaklocale "zh"

\XeTeXlinebreakskip = 0pt plus 1pt

% deal with nuts floating figures

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

1.4 PDF: template

    template: two-col.latex
      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:


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


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

    echo = FALSE, # No display code chunks
    message = FALSE,
    warning = FALSE,
    dev='svg', # or 'svglite' for multibite characters
    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


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:


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

`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.


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


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}