What is R Markdown?


Useful for reproducible science - data, code, and output all in one place! You can creaste: PDFs, webpages, theses/ books, HTML slides, powerpoint presentations and more.

R Markdown anatomy


Three main parts:

  1. Yet another markdown language -> there is an addin to assist called ymlthis here
  2. Setup (see below)
  3. Code chunk or a window into R - code as you would normally

YAML themes


You can customise how HTML documents look by using different themes - https://bootswatch.com/

The themes are:

“default”, “cerulean”, “journal”, “flatly”, “darkly”, “readable”, “spacelab”, “united”, “cosmo”, “lumen”, “paper”, “sandstone”, “simplex”, “yeti”

Here are some more theme options:

Set-up


Your first code chuck is for document setup and it has the documents global options including a call to knit your code chunks. Something like below where tidy=TRUE and there is a width.cutoff will keep the code withing the box and help to keep your code consistent and tidy throughout.

R workflow


This is what your workflow might look like:

This is what your workflow could look like:

Resources for R Markdown


  1. If you are interested in making a book, blog, or website there is guidance here

  2. If you want to know more about Markdown, check out “R Markdown: The Definitive Guide” here

  3. papaja can be used for wrtiting mansuscipts/ theses here

  4. If you use Zotero, there is an add-in to use it in Markdown, click here

  5. pagedown for creating pdf’s without using latex, here

  6. Want to make beautiful slideshows? Use xaringan here

  7. The cheatsheet is here

  8. Finally, here is a google document which compiles all Rmarkdown resources here

Hiding the mess


Click here for options, some common ones are include = FALSE to exclude the code and any output or, echo=FALSE to hide the code but show the resulting plot/tables

We can also use a numeric vector to select which R expression(s) to echo in a chunk, e.g. echo=2:3 means only echo the 2nd and 3rd expressions, and echo=-4 means to exclude the 4th expression

Formatting your text


Format text on two lines


Hit return and add two spaces
item 1
item 2

If you don’t add the spaces the output will be as follows;

item 1 item 2

Add space


R   Markdown will ignore  different space sizes, which is a   good thing to keep  text                         formatted correctly

e.g. 

R Markdown will ignore different space sizes, which is a good thing to keep text formatted correctly.

If you do want spaces in your text (HTML), use Non breaking space HTML tag &nbsp

R       Markdown will ignore      different space sizes, which is a   good thing to keep  text    formatted correctly.  

e.g. 

R       Markdown will ignore      different space sizes, which is a good thing to keep text    formatted correctly.

Skip a line


Add spaces in my document to give it a more uncluttered look. This is done using the <br> command.

  1. without <br>

A first sentence
A second sentence

  1. with <br><br><br><br> between the lines we insert 4 spaces

A first sentence



A second sentence

Other formatting


Inserting a quote:

> "*quote*"  - Name

quote

— Name

Inserting a weblink:

[click](www.google.com)

click

Bullets and numbers


* item 1
* item 2   

OR,

- list 1
  + sub-item 1
  + sub-item 2
- list 2

OR,

1. item 1
     + sub-item 1
     + sub-item 2
2. item 2

**Use ’*’ ‘-’ and ‘+’ to insert unordered bullet points**

or

For numbered lists use numbers with full stops

  1. item 1
    • sub-item 1
    • sub-item 2
  2. item 2

or numberes with a closed bracket

  1. item 1
    • sub-item 1
    • sub-item 2
  2. item 2

A collapsible section with markdown


This code

<details>
<summary>Click to expand</summary>

<p>

  Heading  
  
  1. A numbered
  2. list
     * With some
     * Sub bullets
</details>

Produces this dropdown menu

Click to expand

Heading

  1. A numbered
  2. list
    • With some
    • Sub bullets

Heading size options


# Header 1

## Header 2

### Header 3

You can use # to change the size of headings, from one for the largest heading and adding more to get more sub-headings, you’ll notice at the top of this document there is a toc or table of conents option. This uses these heading to create a toc.

this is small heading
this is small italic heading

Plots


carplot <- ggplot(cars) + geom_point(mapping = aes(x = dist, 
    y = speed)) + theme_bw()

Let’s now draw the carplot with print(carplot). Note the caption in the header with fig.cap=

print(carplot)
Figure 1: My first Markdown plot.

Figure 1: My first Markdown plot.

SlickR


plotsToSVG <- replicate(5, {
    svglite::xmlSVG(code = {
        x <- sample(1:5, 1)
        plot(stats::density(stats::rnorm(10 * x, sd = x)))
    }, standalone = TRUE)
}, simplify = FALSE)

slickR::slickR(plotsToSVG, height = 200, width = "95%")

Interactive plots!


library(plotly)
library(gapminder)

p <- gapminder %>% filter(year == 1977) %>% ggplot(aes(gdpPercap, 
    lifeExp, size = pop, color = continent)) + geom_point() + 
    scale_x_log10() + theme_bw()

ggplotly(p)

Two figures side by side


You can display 2 plots one beside each other. Add out.width=c(‘50%’, ‘50%’), fig.show=‘hold’ to your chunk header:

boxplot(1:10)
plot(rnorm(10))

Tables

Use Kable, for more information see click here

kable(mtcars[1:5, ], caption = "Table 1. My first Markdown table")
Table 1. My first Markdown table
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2

Interactive tables!


library(DT)
datatable(mtcars, rownames = TRUE, filter = "top", options = list(pageLength = 5, 
    scrollX = T))

Equations


Insert equation using Latex formating where Latex syntax is delimited with $

${\displaystyle {\text{AM}}={\frac {1}{n}}\sum _{i=1}^{n}a_{i}={\frac {a_{1}+a_{2}+\cdots +a_{n}}{n}}}$

\({\displaystyle {\text{AM}}={\frac {1}{n}}\sum _{i=1}^{n}a_{i}={\frac {a_{1}+a_{2}+\cdots +a_{n}}{n}}}\)

Inline code


We can also use inline text to add stats into text. by writing r then the object of interest surounded by backticks.

For an easy example this code when wrttien in Markdown

1 + 8 = `r 1+ 8`

Produces this; 1 + 8 = 9

You can also link to model output if you want to summarise data

model_fit <- lm(dist ~ speed, data = cars)
b <- coef(model_fit)
b
## (Intercept)       speed 
##  -17.579095    3.932409

Use this code to insert the interecpt, 1st column [1] and rouded to 2pm

r round(b[1], 2)

The intercept of the regression is -17.58 and the slope of the regression is 3.93

Highlighting

Use the following code:

<style>
div.blue { background-color:#e6f0ff; border-radius: 5px; padding: 20px;}
</style>
<div class = "blue">

- R Marksdown provides an easy work-flow
- Writing and data can be published straight from R in many formats

</div>

To produce:

  • R Marksdown provides an easy work-flow
  • Writing and data can be published straight from R in many formats

Export as a PDF?


One of the easiest ways is to have installed a version of LaTeX- such as TinyTeX or MiKTeX. Use the code below to automatically istally TinyTex. Another option is to use pandoc/ pagedown to buypass LaTex

tinytex::install_tinytex()

Tips


  1. Remember: Knit early. Knit often - this way you’ll find errors as you go.
  2. code_folding: "hide" if you are sending your document to people focused on the results.
  3. number_sections: TRUE if you want chapter/ section numbers.
  4. use ctrl alt i to insert a code chunk.
  5. Label your code chunks so you can easily find them later.
  6. There is an add-in to format the YAML.