---
title: "Workshop on R-Markdown"
author: "Yeamin Faria Chowdhury & Michael Tiefelsdorf"
date: "`r Sys.Date()`"
output:
  html_document:
    toc: yes
    toc_float:
      collapsed: no
      smooth_scroll: no
    number_sections: yes
    toc_depth: 2
---
::: {.section .heading style="color: green;"}
# Introduction
:::

R Markdown is dynamic authoring tool that allows one to combine in one documents R code, its output and text. There are four types of input to be concerned with while working with R markdown,\

1. **Metadata**: In the beginning of the document is the YAML header, which is enclosed by `---`. It contains information about the general appearance of the document, e.g., pdf, html or PowerPoint and choice of fonts, table of content etc.

2. **Global** `R` options
The global `R` options apply to all code chunks, but they can be overwritten in individual code chucks. See the example below:

```{r, setup, include=TRUE, echo=TRUE}
##
## Setting global options, which apply to the whole document
##
knitr::opts_chunk$set(
  error = TRUE,         # document will knit even if code chunk contains error
  fig.align = 'center', # center graphs on the page
  out.width = '90%',    # graphs take 90% of available width
  warning = FALSE,      # prevents warnings in the knitted output
  message = FALSE,      # prevents messages in the knitted output
  size = 'small',       # slightly smaller LaTeX output
  tidy = FALSE          # shows code like you wrote it
)
```
3. **Formatted Text**: It contains the explanation on the code, beackground information, analysis interpretations etc. The text can be formatted by fairly straightforward formatting commands.\

4. **Code chunks**: They contain the `R` code to be executed which is denoted by ```` (```{R}) ```` at the beginning of the chunk and ```` (```) ```` at the end. The output can also be included if needed. For writing a code inline within the text, you can just use one tick (`). Here your `R` code needs to be encompassed by one tick. \   

Two brief documents provide an easily accessible introduction to R Markdown:

1. [Chapter 11 Introduction to R Markdown in "Geospatial Health Data: Modeling and Visualization with R-INLA and Shiny"](https://www.paulamoraga.com/book-geospatial/sec-rmarkdown.html)

2. [Chapter 27: R Markdown as well as Chapters 29 and 30 in "R for Data Science"](https://r4ds.had.co.nz/r-markdown.html). The R Markdown version of this book can be found on [github](https://github.com/hadley/r4ds)

::: {.section .heading style="color: green;"}
# Text Formatting
:::

## Headings and Sections

Headings and sections of different levels are created with `#`.

-   `#` indicates first level
-   `##` indicates second level, and so on.

Unordered list is created using `-`, `*` or `+` and one list within another list can be created by indenting the sub-list as below: 

- Item 1
    - Sub-item 1.1
        - Sub-sub-item 1.1.1
            - Sub-sub-sub-item 1.1.1.1
- Item 2
- Item 3  

Ordered list items are created with numbers, e.g., 

1. Item 1
2. Item 2
    - one unordered item

## Font styles and effects

-   *Italic text*: `*text*` or `_text_`

-   **Bold text**: `**text**` or `__text__`

-   `Typewriter (code) text`: `text`

-   Endash (`--`), emdash(---): `--` and `---`

-   ^superscript^ and ~subscript~: `^superscript^` and `~subscript~`

-   ~~strikethrough~~: `~~strikethrough~~`

-   Footnote[\^1]: `Footnote^[1]`

##  Manual line breaks 
Multiple sentences can be written by using `\` or by pressing `space key` two times and then hitting `Enter` and then starting the new sentence.

## Blockquotes 
Blockquotes are written after >, e.g.,  
`> "The way to learn a new programming language is by writing programs in it.">> --- Dennis Ritchie`  

And the output looks like this: 

> "The way to learn a new programming language is by writing programs in it."
>
> --- Dennis Ritchie

##   Adding links  
`[wikipedia](http://wikipedia.com)`  

The output looks like this:  

[wikipedia](http://wikipedia.com)

## Text Color 
Text blocks can be set to a different color by changing the style option which is written as:\
    `::: {.greeting .heading style="color: red;"} Hello **world**! :::`  
    
And the output looks like this:  

::: {.greeting .heading style="color: red;"} 
Hello **world**! 
:::

## Cross referencing within document 
The figures, tables and equations can be cross referenced, which is a useful way of directing the readers through the document. To do so, three conditions are to be met:\
    - **A bookdown output format**: As cross referencing is provided as an extension in in bookdown, we must therefore use an output format from bookdown (e.g., `html_document2`, `pdf_document2`, and `word_document2`, etc.) in the YAML `output` field.\
    - **A caption to the figure/table **: Without a caption, the figures/tables cannot be identified.\
    - **A labeled code chunk**: This provides the identifier for referencing the figure generated by the code chunk.  
    
After these, we can cross-reference within the text using the syntax `\@ref(type:label)`, where label is the chunk label and type is the environment being referenced (e.g. tab, fig, or eq).
    

##   Tables
- One way to print table is to simply run it from the code chunk:  
```{r table-1}
data <- trees[1:4, ]
data
```

- Simple tables look like this: 
`| First Header | Second Header |
|--------------|---------------|
| Content Cell | Content Cell  |
| Content Cell | Content Cell  |`

| First Header | Second Header |
|--------------|---------------|
| Content Cell | Content Cell  |
| Content Cell | Content Cell  |  

- Pipe table look like this (useful for table alignment):

`|   Source    |  df  |   Sum of Sq   |    Mean Sq    |    F   |  $Pr(>F_{1,29})$    |
|:------------|-----:|--------------:|--------------:|-------:|--------------------:|
|  Girth      |  1   |  7581.8       |  7581.8       | 419.26 |  **< 2.2e-16**      |
|  Residual   |  29  |  524.3        |   18.1        |        |                     |`


|   Source    |  df  |   Sum of Sq   |    Mean Sq    |    F   |  $Pr(>F_{1,29})$    |
|:------------|-----:|--------------:|--------------:|-------:|--------------------:|
|  Girth      |  1   |  7581.8       |  7581.8       | 419.26 |  **< 2.2e-16**      |
|  Residual   |  29  |  524.3        |   18.1        |        |                     |

- You can also insert table by using the 'kable' function from the 'knitr' package:
    
```{r tables-mtcars}
knitr::kable(iris[1:5, ], caption = 'A caption')
```

##   Inserting images
`![Fig: R Markdown hex logo](logo.png)`  

The output looks like this:  

![Fig: R Markdown hex logo](logo.png)  

To get more control over the attributes of the image, you may use the `knitr::include_graphics()` function:  

````{r, out.width='25%', fig.align='center', fig.cap='R Markdown hex logo'}knitr::include_graphics('logo.png')````  

And the output looks like this:

```{r, out.width='25%', fig.align='center', fig.cap='R Markdown hex logo'}
knitr::include_graphics('logo.png')
```


::: {.section .heading style="color: green;"}
# Code Chunks
:::

The code chunk is given  either by typing three back ticks at the top and bottom or by using the RStudio toolbar (the `Insert` button) or by using the keyboard shortcut Ctrl + Alt + I (Cmd + Option + I on macOS). The R-codes are written and run inside the chunks. After execution, the output of the code appears below the code chunk \@ref(fig:snippet-plot).\  

```{r snippet-plot, echo=TRUE, include=TRUE, fig.height=4, fig.width=4, fig.cap = "The plot for x vs x^2"}
x <- seq(0.1, 2, by=0.1) 
plot(x,x^2, type="l", col="red")
```

This is written as ```` ```{r snippet-plot, echo=TRUE, include=TRUE, fig.height=4, fig.width=4, fig.cap = "The plot for x vs x^2"}) ````\  

There is an option of naming the chunks - `{r by-name}`. This is especially useful while troubleshooting an error in the document. The source error could be tracked down by the chunks name. If the label or name of a chunk is missing, a default one of the form `unnamed-chunk-i` will be generated, where `i` is incremental.\  

There are many chunk options available for customizing code chunks in r markdown document, the output which won't be shown in the document. The chunk name and the code chunk options are written inside the curly braces (between ````{r` and `}`) and are separated by commas. Almost 60 chunk options are documented in the knitr package [here](https://yihui.org/knitr/options/).  

If a certain option needs to be frequently set to a value in multiple code chunks, you can consider setting it globally in the first code chunk of your document.  

## Figures
To place multiple figures side-by-side from the same code chunk, you can use the `fig.show='hold'` option along with the `out.width` option. Figure \@ref(fig:side-plot) shows an example with two plots, each with a width of `50%`.  

````{r side-plot, echo=TRUE, include=TRUE, fig.show = "hold", out.width = "50%", fig.align = "default", fig.cap = "Side by side plot"}plot(cars, pch = 19)plot(pressure, pch = 17)````  

And the output looks like this:  

```{r side-plot, echo=TRUE, include=TRUE, fig.show = "hold", out.width = "50%", fig.align = "default", fig.cap = "Side by side plot"}
plot(cars, pch = 19)
plot(pressure, pch = 17)
```

## Some keyboard shortcuts

| Task                  | Windows & Linux  | macOS                |
| :-------------------- | :--------------: | -------------------: |
| Insert R chunk        | Ctrl+Alt+I       | Command+Option+I     |
| Preview HTML          | Ctrl+Shift+K     | Command+Shift+K      |
| Run all chunks above  | Ctrl+Alt+P       | Command+Option+P     |
| Run current chunk     | Ctrl+Alt+C       | Command+Option+C     |
| Run current chunk     | Ctrl+Shift+Enter | Command+Shift+Enter  |
| Run next chunk        | Ctrl+Alt+N       | Command+Option+N     |

Table: R Markdown keyboard shortcuts

## Saving the code chunks only:
Workflow generating and executing chunks can be done using the syntax, `knitr::purl("Doc.Rmd", documentation = 0)`

::: {.section .heading style="color: green;"}
# YAML header
:::

YAML header stands for "yet another markup language'. YAML header contains YAML arguments - 'title', 'author' and 'output', demarcated by three dashes (-) on either end.

-   Title: The title in the YAML header - `(title: "My Title")` will appear at the top of the document with font larger than rest of the document.

-   Author: Author's name can be specified which will appear at the head of the document below the title

-   Date: Date can be specified at the header which will be added to the head of the document. Date can be set as static or dynamic. Using the `Sys.Date()` function will update the `date` field in the YAML each time the document is knitted.

-   Other YAML options:

    -   toc: true/false to show table of contents. The headings of the document is directly reached from this link.
    -   toc_depth: This determines how many subheadings will be visible in the TOC\
    -   toc_float: true/false determines whether the TOC stays visible upon scrolling.\
    -   number_sections: true/false organizes the document with numeric headings\
    -   code_folding: true/false displays code in collapsible sections. It can be one of "none", "hide", "show".\
    -   theme: Change the overall look of the report. It can be one of "default", "cerulean", "journal", "flatly", "darkly", "readable", "spacelab", "united", "cosmo", "lumen", "paper", "sandstone", "simplex", "yeti".

-   References: References can be added `bibliography: filename.filetype` to the header. Learn more about creating citations in the .Rmd file [here](https://r4ds.had.co.nz/r-markdown.html#yaml-header).

::: {.section .heading style="color: green;"}
# Output options
:::

This is the part of the header where you specify the format in which you want to publish your document. Some output format of interest are:

-   output: html_document
-   output: ioslides_presentation
-   output: pdf_document
-   output: word_document (.docx)
-   output: odt_document for OpenDocument Text documents (.odt).
-   output: rtf_document for Rich Text Format (.rtf) documents.
-   interactive shiny apps

::: {.section .heading style="color: green;"}
# Notebook (HTML Document)
:::

R Notebook is a document type in R markdown which is more interactive, where the code chunks are executed one at a time. Instead of knitting into different formats, the `Preview` option in R notebook allows to view the output document in the viewer pane. Saving a notebook .Rmd creates a .nb.html file along with the .rmd file automatically, which can be viewed in any browser and shared with others.

::: {.section .heading style="color: green;"}
# Presentations
:::

R markdown can also be used to produce presentations, where the results of the R code is saved into a presentation slides and is very efficient. This can be obtained by rendering the R markdown file in PowerPoint, so that the produced document is rendered in Microsoft PowerPoint. Upon saving the document, when it is knitted, you can render a simple PowerPoint file from the document output. Each slide will begin with a first level (`#`) or second level (`##`) header, or by inserting horizontal rule (`***`) to create a new slide without a header.\
Built in three presentation formats are:

1.  `ioslides_presentation` - HTML presentation with ioslides

2.  `slidy_presentation` - HTML presentation with W3C Slidy

3.  `beamer_presentation` - PDF presentation with LaTeX Beamer.

::: {.section .heading style="color: green;"}
# LaTex Output
:::

In R markdown, LaTex language is used to process equations. There are two writing modes for mathematical expression: Inline math mode and Display math mode.

## Inline Equations:

Inline math equations are put in between single dollar sign. Thus, $\hat{\sigma}^2=\frac{1}{n-1} \cdot \sum_{i=1}^n{(x_i-\bar{x})^2}$ can be written as: `$\hat{\sigma}^2=\frac{1}{n-1} \cdot \sum_{i=1}^n{(x_i-\bar{x})^2}$`.

## Display Equations:

In order to write equations in Display mode, we start with two dollar signs (`$$`) at either ends. Anything between these signs will be processed as equations. Such as, $$
\hat{\sigma}^2=\frac{1}{n-1} \cdot \sum_{i=1}^n{(x_i-\bar{x})^2}
$$ is written as: `$$ \hat{\sigma}^2=\frac{1}{n-1} \cdot \sum_{i=1}^n{(x_i-\bar{x})^2} $$`

::: {.section .heading style="color: green;"}
# Some cheatsheets
:::
1. [evoldyn.gitlab.io](https://evoldyn.gitlab.io/evomics-2018/ref-sheets/rmarkdown-2.0_layout2.pdf)
2. [www.rstudio.com](https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf)  

::: {.section .heading style="color: green;"}
# Web-Reference links
:::
1. [R Markdown: The Definitive Guide](https://bookdown.org/yihui/rmarkdown/)
2. [A Sufficient Introduction to R](https://dereksonderegger.github.io/570L/1-introduction.html)
3. [R Markdown Cookbook](https://bookdown.org/yihui/rmarkdown-cookbook/)
4. [R Markdown Crash Course](https://zsmith27.github.io/rmarkdown_crash-course/index.html)


