Aims:

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 to write your markdown. RStudio 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

R markdown like most other flavours builds on top of standard markdown. It has some R language specific features as well as bunch of general enhancers to markdown. When Rmarkdown is coupled with Rstudio 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)


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

The R code blocks section


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

Everything else is plain old markdown


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

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

 # Header1
 ## Header2
 ### Header3

 Paragraphs are separated
 by a blank line.

 Two spaces at the end of a line
 produces a line break.

 Text attributes _italic_,
 **bold**, `monospace`.

 Horizontal rule:

 ---

 Bullet list:

   * apples
   * oranges
   * pears

 Numbered list:

   1. wash
   2. rinse
   3. repeat

 A [link](http://example.com).

 ![Image](Image_icon.png)

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

 Hello world, I'm learning R markdown !

Hello world, I’m learning R markdown !

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.

 # Hello world, I'm learning R markdown !

Hello world, I’m learning R markdown !


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

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

Hello world, I’m learning R markdown !

Hello world, I’m learning R markdown !

Hello world, I’m learning R markdown !


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

Remember that vanilla markdown 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}
 print("Hello world, I'm learning Rmarkdown")
 ```
print("Hello world, I'm learning R markdown !")
## [1] "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.

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, echo = FALSE}
 print("Hello world, I'm learning Rmarkdown")
 ```
## [1] "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 eval = FALSE}
  print("Hello world, I'm learning R markdown !")
 ```
print("Hello world, I'm learning R markdown !")

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

Here is nice cheatsheet 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}
 summary(cars)
 ```
summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

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}
 plot(cars)
 ```
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 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 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 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, 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)")
 ```
**Figure: 1** This figure illustrates breaking distance as a function of travelling speed

Figure: 1 This figure illustrates breaking distance as a function of travelling speed

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 and R slides 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}
 sentence <- c("Let", "the", "computer", "do", "the", "work")

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

for(word in sentence){
  print(word)
}
## [1] "Let"
## [1] "the"
## [1] "computer"
## [1] "do"
## [1] "the"
## [1] "work"

These two options are cosmetis:

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 prompt=TRUE, comment="//"}
 sentence <- c("Let", "the", "computer", "do", "the", "work")

 for(word in sentence){
   print(word)
 }
 ```
> sentence <- c("Let", "the", "computer", "do", "the", "work")
> 
> for(word in sentence){
+   print(word)
+ }
// [1] "Let"
// [1] "the"
// [1] "computer"
// [1] "do"
// [1] "the"
// [1] "work"

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

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.

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

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

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

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

 ---
 output: ioslides_presentation
 ---

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 and give you some extra tips about it. Hopefully this will grow into section of it own in the near future.