Here’s a precise manual I put together for convenient learning of Rmarkdown and as an easy reference. Bookmark or re-download periodically as I will keep updating this page for improvement.


\[\\[0.4in]\]

Good guide: https://bookdown.org/yihui/rmarkdown/

Install

Install Rmarkdown (in R)

install.packages("rmarkdown")

\[\\[1in]\]

Document types and header

Types of output documents

  • html_notebook - Interactive R Notebooks

  • html_document - HTML document w/ Bootstrap CSS

  • pdf_document - PDF document (via LaTeX template)

  • word_document - Microsoft Word document (docx)

  • odt_document - OpenDocument Text document

  • rtf_document - Rich Text Format document

  • md_document - Markdown document (various flavors)

  • ioslides_presentation - HTML presentation with ioslides

  • revealjs::revealjs_presentation - HTML presentation with reveal.js

  • slidy_presentation - HTML presentation with W3C Slidy

  • beamer_presentation - PDF presentation with LaTeX Beamer

  • powerpoint_presentation: PowerPoint presentation

  • flexdashboard::flex_dashboard - Interactive dashboards

  • tufte::tufte_handout - PDF handouts in the style of Edward Tufte

  • tufte::tufte_html - HTML handouts in the style of Edward Tufte

  • tufte::tufte_book - PDF books in the style of Edward Tufte

  • html_vignette - R package vignette (HTML)

  • github_document - GitHub Flavored Markdown document

  • You can also build books, websites, and interactive documents with R Markdown.

Header for HTML document

title: mytitle
author: name
date: January 1, 2015
output:
 html_document:
  includes:
   in_header: [“some.html”, “some.js”]   #include header html or javascript
  css: “style.css”   theme: default  #other options below
  highlight: tango  #specifies the syntax highlighting style
  logo: header.jpeg  #adds a logo in header
  code_folding: show
  toc: true  #include table of contents
  toc_depth: 4   #upto three depths of headings specified by #, ## and ###
  toc_float: TRUE  #float the table of contents to the left of the main document content   number_sections: false # number headings
urlcolor: gray
citecolor: gray
params:
 data: “hawaii”  #define parameters and read within code as params$data etc.
bibliography: mybib.bib

=>NOTE: Available themes: cerulean, journal, flatly, darkly, readable,
        spacelab,united, cosmo, lumen, paper, sandstone, simplex, yeti


Header for PDF document

\[\\[1in]\]

Customize using css

<style type="text/css"> 
  .main-container       /*for whole page*/
  {
    max-width: 650px;   /*overall width of the HTML page*/
    margin-left: auto;  /*or 10%, 20px etc.*/
    margin-right: auto; /*setting auto for both centers content*/
  }
  body, td              /*for body*/
  {
     font-size: 16.5px;
     font-family: Calibri;
     background: rgb(250,250,250);
  }
  h1.title 
  {                    /*Heading 1 title*/
     font-size: 38px;
     color: DarkRed;
  }
  h1                   /*Heading 1*/
  { 
     font-size: 28px;
     color: DarkBlue;
  }
  h2                   /*Heading 2*/
  { 
     font-size: 22px;
     color: DarkBlue;
  }
  h6                   /*Heading 6*/
  { 
    font-size: 18px;
    font-family: "Times New Roman", Times, serif;
    color: DarkBlue;
  }
  code.r               /*for r codes*/
  {                     
    font-size: 16.5px;
  }
  pre                  /*for output of knitr chunks*/
  {                     
    font-size: 16.5px
    border: 0;
  }
  #TOC {               /*for table of contents*/
    color: purple;
    font-size: 15px;   
    margin: 10px 0px 20px 0px;
  }
  .toc-content {       /*for padding of text in table of contents*/
  padding-left: 30px;
  padding-right: 40px;
}
</style>

\[\\[1in]\]

Text formating

Bold: **Bold** or __Bold__

Italics/Emphasize: Italics or Italics

Bold and Italics: ***Bold and Italics*** or ___Bold___

code: {r cat('code')

Subscript, superscript: subscript~2~, superscript^2^

Strikethrough: ~~strikethrough~~

Escaped: \*, \_, \\

Dash: endash --, emdash ---

link: [linktext](link_URL){target="_blank"} or [linktext][id] and at the end of document [id]:link_URL

References: Shown by this paper [@markdown15] #bibliography entry

Inline latex equation: $a = b^2$ # no space after/before first/last $

Blockquote: start a paragraph with >

Headers: # Heading 1, ## Heading 2, ### Heading 3

Unordered List:

- Item 1
  - Item 1.1
    - Item 1.2
      - Item 1.1.1
        - Item 1.1.1.1   #keep shifting by two spaces
- Item 2

Ordered List:

1. Item 1
2. Item 2
3. Item 3
    - Item 3a    #keep shifting by two spaces
    - Item 3b

Add  before an underscore(_) to stop getting boldfaced/red lines.

\[\\[1in]\]

Include image

Using markdown

![Image caption](foo.png){width=80%}

or

![Image caption][id] and at the end of document [id]: foo.png

Using R

knitr::include_graphics("foo.png")

\[\\[1in]\]

R codes

R code inline

date: `r Sys.Date()`

R code chunk

```{r label, eval=T, echo=F, results='hide', include=F, message=F, warning=F, 
    fig.cap="Bla", fig.width=12, fig.height=10, out.width=80%, comment="##",
    tidy=F, tidy.opts = list(width.cutoff=90, arrow=T, indent=2),
    error=F, child=NULL}
x = 1:5
y = x^2
```
=>NOTE: reference the chunk output figure by \@ref(fig:label), table by
            \@ref(tab:label), equation by \@ref(eq:label) [figure/table
            must be captioned]. All of these need bookdown formats
            html_document2, pdf_document2, word_document2 etc.
        eval: Evaluates the code
        echo: F prevents code, but not the results, from appearing in the
              output. Useful way to embed figures.
        results: 'markup' is default, 'hide' hides the results, 'asis'
                  shows commented out results, 'hold' shows all results
                  commented out below all code.
        include: F prevents code and results from appearing in the output
                 but codes will still be evaluated and the results can 
                 be used by other chunks.
        message: F prevents messages generated by code from appearing in
                 the output.
        warning: F prevents warnings generated by code from appearing in
                 the output.
        out.width: rescales output width, e.g. "75%", "300px".
        comment: prefix for each line of results,
        tidy: R source code will be reformatted by the 
              formatR::tidy_source() function. Adds spaces around most 
              operators, indents the code properly, and replaces the 
              assignment operator = with <-.
        error: If T show error msg in doc, if F stop render if errors
        child: files(s) to knit and then include.

Collapse code and outcome in one block

```{r, collapse=T} print(1:4) ```

print(1:4)
## [1] 1 2 3 4

R chunk global options setting

```{r global_options, include = F}
knitr::opts_chunk$set(echo = T)
options(width = 150)  
```
=>NOTE: To set global options that apply to every chunk in your file, call
        knitr::opts_chunk$set in a code chunk. Knitr will treat each option
        that you pass to knitr::opts_chunk$set as a global default that can
        be overwritten in individual chunk headers.

\[\\[1in]\]

Other language codes

Bash code chunk

```{bash}
ls *.Rmd
```

Python code chunk

```{python}
x = ‘hello’
print(x)
```

\[\\[1in]\]

Cross-referencing

For cross-referencing, needs output document type bookdown::html_document2 with number_sections: yes.

Reference a heading # BlaBla {label} by Section \@ref(label)

Reference the captioned figure from a chunk {r, label, fig.cap="bla"} by Figure \@ref(fig:label).

Reference the captioned table from a chunk {r, label} by Table \@ref(tab:label).

Reference the captioned equation from a chunk {r, label} by Table \@ref(eq:label).

Reference and embed chunks within other chunks

```{r, chunk1}
x <- 1
```
```{r, chunk2}
y <- 2
```
```{r, chunk3}
<<chunk1>>
<<chunk2>>
```

echo of chunk3 will be

x <- 1
y <- 2

\[\\[1in]\]

Make tables

Using R

library(kableExtra)
knitr::kable(head(iris), caption="Using knitr::kable()")
Table 1: Using knitr::kable()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa
kableExtra::kable(head(iris), format="html", 
            table.attr= "style='width:35%;'", 
            caption="<center><strong>Center the caption</strong></center>",
            escape=FALSE) %>% 
  kableExtra::kable_styling()   #many options within
Table 1:
Center the caption
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa


Manually

| First Header  | Second Header | Third Header         |
| :------------ | :-----------: | -------------------: |
| First row     | Data          | Very long data entry |
| Second row    | **Cell**      | *Cell*               |
| Third row     | Cell that spans across two columns  ||

Table: Your Caption
Your Caption
First Header Second Header Third Header
First row Data Very long data entry
Second row Cell Cell
Third row Cell that spans across two columns

\[\\[1in]\]

HTML Tabsets

# Results {.tabset} 

## Tab 1 
content

## Tab 2  
content

\[\\[1in]\]

Printing code verbatim

Inline code

To print `r 2+3` use <code>&grave;r 2+3&grave;</code>

To print the right expression above wrap it with double backticks

(backtick is \x60 in the hex code and &grave; in html)

Another trick: This will show the same verbatim inline R expression

`` `r
2+3` ``

Code chunk

Use verbatim with n+1 backticks to print a chunk with n backticks.

```{verbatim}
`` `r
2+3` ``
```

\[\\[1in]\]

Render from commandline

$ echo "rmarkdown::render('sample.Rmd', clean=TRUE)" | R --slave

or

$ Rscript -e "rmarkdown::render('sample.Rmd', clean=TRUE)"

\[\\[1in]\]

\[\\[3in]\]