<style>
.code-exmpl {
border-style: solid;
border-width: 1px;
border-color: #e6e6e6;
border-radius: 3px;
background: #f2f2f2;
padding: 10px;
width: 89%;
margin: auto
}
</style>

---
title: "R markdown"
output: html_document
---

>  Aims:
>
> - Learn to write and compile Rmarkdown documents
>
> - Learn to embed R code into markdown documents
>
> - Learn a couple of different output documents types
>

# Introduction to markdown

Markdown is a powerful "language" for writing different kinds of documents, such as **PDF** or **HTML** in an efficient way, but markdown documents can also be published as is. The underlying idea for then markdown is that it is easy-to-write and easy-to-read.

You can use any [text editor](https://en.wikipedia.org/wiki/Text_editor) to write your markdown. [RStudio](https://rstudio.com) already has inbuilt text editor and because it also has a few additional things that make markdown writing much easier we are going to use it's text editor.

There are a few different flavours of markdown around. I'm going to mention a few but only focus on one, [Rmarkdown](https://rmarkdown.rstudio.com/)

- [CommonMark](http://commonmark.org/)
- [GitHub Flavored Markdown (GFM)](https://guides.github.com/features/mastering-markdown/)
- [Rmarkdown](https://rmarkdown.rstudio.com/)

[R markdown](http://rmarkdown.rstudio.com/) like most other flavours builds on top of standard markdown. It has some [R language](https://www.r-project.org/) specific features as well as bunch of general enhancers to markdown. When [Rmarkdown](http://rmarkdown.rstudio.com/) is coupled with [Rstudio](https://rstudio.com) it creates a powerfull means of documenting your work while you are doing it, which you can then share with colleagues and the public in rapid and clean way.

Let's get right into it. Open **R Markdown file** using these drop down menu steps: **File** -> **New File** -> **R Markdown**. You can put any `title` and any `author` name. For now select **Document** and Document type **HTML**. Once you have opened your `.Rmd` file, click on the `Knit HTML` button at the top of your pane.

`Knitr` is an R package that does all the magic of converting and running your R markdown and R code respectively.

These are three main parts to any R markdown document

#### [YAML header section (will talk about it at the very end)](#yaml-header)

```

`r ''` ---
`r ''` title: "Hello world"
`r ''` author: "Kirill"
`r ''` date: "13 July 2016"
`r ''` output: html_document
`r ''` ---

```

#### [The R code blocks section](#r-code-in-r-markdown)

````

`r ''` ```{r}
`r ''` plot(pressure)
`r ''` ```

````

#### [Everything else is plain old markdown](#markdown-basics)

````

`r ''` # Have I been Marked Down ?

````

# Document types

There are numerous document types that you can turn your markdown into. This all depends on the tool, markdown compiler, but for [Rstudio](https://rstudio.com) at least these a few that a supported.

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

#### Presentations (slides)

- `ioslides_presentation` - HTML presentation with ioslides

#### More

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

[**More here**](https://rmarkdown.rstudio.com/lesson-9.html)

We are not going to cover all of them, we are mainly going to be working with either `html_notebook` (new way) or `html_document` both produce very similar result, and essentially the personal preference. I'll try to touch on `ioslides_presentaion` towards the end.

# Vanilla Markdown

There actually not that much to core (vanilla) of markdown essentially all of it can be summarised below

````
`r ''` # Header1
`r ''` ## Header2
`r ''` ### Header3
`r ''`
`r ''` Paragraphs are separated
`r ''` by a blank line.
`r ''`
`r ''` Two spaces at the end of a line
`r ''` produces a line break.
`r ''`
`r ''` Text attributes _italic_,
`r ''` **bold**, `monospace`.
`r ''`
`r ''` Horizontal rule:
`r ''`
`r ''` ---
`r ''`
`r ''` Bullet list:
`r ''`
`r ''`   * apples
`r ''`   * oranges
`r ''`   * pears
`r ''`
`r ''` Numbered list:
`r ''`
`r ''`   1. wash
`r ''`   2. rinse
`r ''`   3. repeat
`r ''`
`r ''` A [link](http://example.com).
`r ''`
`r ''` ![Image](Image_icon.png)
`r ''`
`r ''` > Markdown uses email-style > characters for blockquoting.
````

## Practice vanilla markdown

Now it's just a matter of learning some of the markdown syntax. Let's delete all current text from the opened document except the YAML header and type this new text in `Hello world, I'm learning R markdown !` and pressing the `Knit HTML` button.

````
`r ''` Hello world, I'm learning R markdown !
````

<div class="code-exmpl">
Hello world, I'm learning R markdown !
</div>

Not much happened. This is because we didn't mark our text in any way. You can put as much text as you want and it will appear as is, unless "specially" marked to look differently.

Now add the `#` symbol at the start of the line and press the `Knit HTML` button again. We'll be pressing this button a lot! For those who like keyboard short cuts use `ctrl+shift+k` instead.

````
`r ''` # Hello world, I'm learning R markdown !
````

<div class="code-exmpl">
<h1> Hello world, I'm learning R markdown !</h1>
</div>

---

How about now? A single hash symbol made it whole lot bigger didn't it? We've marked this whole line to be the header line.

Now make three new lines with the same text, but different numbers of `#` symbols, one, two and three respectively and keep pressing the `Knit HTML` button

````
`r ''` ### Hello world, I'm learning R markdown !
`r ''` ## Hello world, I'm learning R markdown !
`r ''` # Hello world, I'm learning R markdown !
````

<div class="code-exmpl">
<h3> Hello world, I'm learning R markdown !</h3>
<h2> Hello world, I'm learning R markdown !</h2>
<h1> Hello world, I'm learning R markdown !</h1>
</div>

---

This is how you can specify different headers type using markdown.

**Remember** that [vanilla markdown](https://daringfireball.net/projects/markdown/syntax) is comprised entirely of punctuation characters.

# Rmarkdown

The most useful thing about [Rmarkdown]() for us as researchers / data analysists is the ability to embed R code in markdown. In order to do that we need to use the ` ```{r } ..``` ` syntax, can also use `ctrl+alt+i` keyboard shortcut.

Let's start with a simple `print()` statement and print `Hello world, I'm learning Rmarkdown !` string.

This is what you need to type in your text editor

````
`r ''` ```{r}
`r ''` print("Hello world, I'm learning Rmarkdown")
`r ''` ```
````

```{r}
print("Hello world, I'm learning R markdown !")
```

This is how you embed code into document. One box shows what you've typed in a.k.a your code and the box below it shows your output just like you'd exepct it in the _console_.

We can tweak many things about your output using different options that we can include inside curly brackets e.g ```{r chunk_name, options} ..```.

The two rather common options are `echo=TRUE` and `eval=TRUE` both by default are set to true and this is why I didn't have to pass them in.

  - `echo` means show what has been typed in i.e show the code
  - `eval` means evaluate or execute that code

Sometimes we might want to show the code, but not execute it and other times we might just want to execute it and get the results without actually bore audience with the code.

let's try both of these options one at a time. We start with passing `echo=FALSE` options first

````
`r ''` ```{r, echo = FALSE}
`r ''` print("Hello world, I'm learning Rmarkdown")
`r ''` ```
````

```{r, echo = FALSE}
print("Hello world, I'm learning R markdown !")
```

Okay, we don't see our original `print()` statement. And now let's pass `eval=FALSE` options instead

````
`r ''` ```{r eval = FALSE}
`r ''`  print("Hello world, I'm learning R markdown !")
`r ''` ```
````

````{r, eval = F}
print("Hello world, I'm learning R markdown !")
````

And now we only see `print()` statement and no output.

[Here is nice cheatsheet](http://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf) that has comprehensive cover of all the options you can pass in.

Let's now try a different example and use the `cars` inbuilt dataset for this next example. Just as we are able to access that variable - `cars` in the _console_ we can do the same here.

````
`r ''` ```{r}
`r ''` summary(cars)
`r ''` ```
````

```{r}
summary(cars)
```

**Remembber** You can go between Rmarkdown and _console_, to check your code, at any time. You should see your code block is highlighted differently and you should see a green arrow at the right hand site of that block. Press the green arrow to get an output in the _console_. You can also use `ctrl+enter` to do the same with the keyboard short cut.

How about little data exploration? We are going to start working in the _console_ and then copy interesting bits into R document. In the _console_ check a data type using `class()` function, then get first few rows of the table with `head()`. It looks like a `data.frame` with two columns. Now let's plot our finding so we can share it with others.

````
`r ''` ```{r}
`r ''` plot(cars)
`r ''` ```
````

```{r}
plot(cars)
```

Here is a perfect example where we can hide our code from the viewer, since it isn't most interesting bit about this data. Let's turn `echo=FALSE` options for all our plots below.

Properly labelled plots are very informative, let's do that as well, starting with a title `main="Travelling speed vs Breaking distance"` and then labelling axis, x `xlab="Travelling speed (mhp)"` and y `ylab="Stopping distance (ft)"`

````
`r ''` ```{r echo = FALSE}
`r ''` plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
`r ''` ```
````

```{r echo = FALSE}
plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
```

Okay, this looks much nicer. Let me show you some other useful options that can manipulate figures.

Figure alignment can be done with `fig.align` options e.g ```{r fig.align=default} ..``` default means what ever your style sheet has. The other options are, "left", "center" and "right". let's try one out.

````
`r ''` ```{r echo = FALSE, fig.align = 'right'}
`r ''` plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
`r ''` ```
````

```{r echo = FALSE, fig.align = 'right'}
plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
```

**Remeber** that you can you always execute code in the _console_ by pressing "green arrow" or using keyborad short cut `ctrl+enter`

We know now how to align figure to where we want, how about changing the size of it? We can do that with `fig.height` and `fig.width`, the units are inches. Let's make 4 X 4 inches figure e.g ```{r fig.height=4, fig.widht=4} ..``` and also align the figure to the center

````
`r ''` ```{r echo=FALSE, fig.height=4, fig.width=4, fig.align='center'}
`r ''` plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
`r ''` ```
````

```{r echo=FALSE, fig.height=4, fig.width=4, fig.align='center'}
plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
```

One last thing I'd like to share with you is how to add a figure legend or a caption - with `fig.cap` of course e.g ```{r, fig.cap="This is my legend"} ..``` Go ahead and add a figure description.

````
`r ''` ```{r, echo=FALSE, fig.cap="**Figure: 1** This figure illustrates breaking distance as a function of travelling speed"}
`r ''` plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
`r ''` ```
````

```{r, echo=FALSE, fig.cap="**Figure: 1** This figure illustrates breaking distance as a function of travelling speed"}
plot(cars, main="Travelling speed vs Breaking distance", xlab = "Travelling speed (mhp)", ylab="Stopping distance (ft)")
```

**Note** that the figure legend follows the same alignment as the figure itself.

I'm going to share with you four other options that I find rather useful before moving onto [YAML header](#yaml-header) and [R slides](#r-slides---ioslides) sections.

For this examplel I'm going to use simple `for` loop. We are going to use this variable `sentence <- c("Let", "the", "computer", "do", "the", "work")`

````
`r ''` ```{r}
`r ''` sentence <- c("Let", "the", "computer", "do", "the", "work")
`r ''`
`r ''` for(word in sentence){
`r ''`   print(word)
`r ''` }
`r ''` ```
````

```{r}
sentence <- c("Let", "the", "computer", "do", "the", "work")

for(word in sentence){
  print(word)
}
```

These two options are cosmetis:

  - `prompt=FALSE` is to turn prompt display on or off i.e trying to mimic _consosle_
  - `comment=` this is to change or remove double hash symbol comments to something else

Let's turn prompt on to see whats it looks like e.g ```{r prompt=TRUE} ..``` and change our comments symbol to double forward slash `//`

````
`r ''` ```{r prompt=TRUE, comment="//"}
`r ''` sentence <- c("Let", "the", "computer", "do", "the", "work")
`r ''`
`r ''` for(word in sentence){
`r ''`   print(word)
`r ''` }
`r ''` ```
````

```{r prompt=TRUE, comment="//"}
sentence <- c("Let", "the", "computer", "do", "the", "work")

for(word in sentence){
  print(word)
}
```

The two other options I just would like to mention and will let you explore them at your own leisure.

  - `engine=` you can use to specify different language type. This is very cool. You can actually embed python, BASH JavaScript and nubmer of other languages.
  - `child=` You use this options to "merge" several `.Rmd` into one.

# YAML header

At the very top of your `.Rmd` file you can, optionaly, include YAML block. In this block you can fine turn your output document, add some metadata and change document's font and theme. You can also pass additional files such as stylesheet file `.css` and bibliography file `.bib` for text citation. I'm only going to show you a few possible options and will let you explore the rest on your own.

Navigate to the top of your `.Rmd` document and find YAML section there. Just like with the options we passed in to manipulate R code block, YAML block also has **key = value** pairs, but instead they are separated by colon ( `:` ). Now let's add table of content to our document, this will make it easier to navigate your page as well as give nice over view of the content our **key** is `toc` with value `true` or `yes` which one you prefer better.

````
`r ''` ---
`r ''` title: "Hello world"
`r ''` author: "Kirill"
`r ''` date: "13 July 2016"
`r ''` output:
`r ''`   html_document:
`r ''`     toc: true
`r ''` ---
````

**Note** that you need to bring `html_document` onto new line and indent it with two spaces. `html_document` is a value of `output` key. `output` can have other values e.g `pdf_document`, `word_document`. However `html_document` also becomes a key for `toc` value and `toc` becames a key for its own value.

Now that we have sort it initial YAML layout we can continue adding more options to style our HTML document. The other two useful options that I like to pass in are `toc_depth` and `number_sections`

````
`r ''` ---
`r ''` title: "Hello world"
`r ''` author: "Kirill"
`r ''` date: "13 July 2016"
`r ''` output:
`r ''`   html_document:
`r ''`     toc: true
`r ''`     toc_depth: 4
`r ''`     number_sections: yes
`r ''` ---
````

Most of those options are self explanatory. They best way to learn what each does, is to pass them in. Note that you can comment lines out inside YAML section with `#` symbol.

The last two options that can change your document apperance are `theme` and `highlight`. There are nubmer of different themes and highlight options. I suggest you find the one you like in your own time.

# R slides - ioslides

As I mentioned in previous section, `output` has many options, one of which is `ioslides_presentation`. You can simple add

````
`r ''` ---
`r ''` output: ioslides_presentation
`r ''` ---
````

at the top of your document and your `.Rmd` files will be complied to slide presentation instead.

Another options is select **presentation** options when you were opening R markdown file. Either way you'll notice YAML header reflects your selected output type.
Let's open new R markdown document and let's select presentation instead and let's select HTML (ioslides) option there. You can still save your files as `.Rmd`, and then press the\ the `Knit HTML` button.

The syntax for the document is more or less the same, expcept `##` is now used to mark new slide.

# Extras

This is mainly to talk about [Rnotebook](https://rmarkdown.rstudio.com/r_notebooks.html) and give you some extra tips about it. Hopefully this will grow into section of it own in the near future.

- to turn inline output (defualt behaviour) on R markdown documents on/off through settings, _Chunk output inline_ / _Chunk output in console_
- Output doesn't go to Viewer/Plots pane, it stays inside the notebook
- Working directory is the location of Rmd file. (I think changing directory with in the chunk isn't good idea)
- In general [Rnotebook](https://rmarkdown.rstudio.com/r_notebooks.html) meant to have better error handling, sends one line at a time for execution, compare to all lines for Rmarkdown document
