Lesson 8 RMarkdown - Output formats

8.1 Learning outcome:

After this lesson you will be able to

  1. Have an overview of different output formates for RMarkdown and render those formats.
  2. Setup github pages
  3. Create a bookdown project
  4. Render a bookdown project to a local website (aka html pages)
  5. Add the rendered site to your github pages

8.2 Easy start: job interviews

Before we start diving into RMarkdown again, read the following blog post. While you can see that we (the teachers) may have a slightly different opinion in some aspects (e.g. tidyverse!), it gives a nice checklist for you to scan on general R knowledge. Do keep in mind that these kind of questions would not appear on a life sciences job interview. click

8.3 Output possibilities

With Rmarkdown you can generate many different things. This reader was made in Rmarkdown. The DAUR1 exam? RMarkdown. Daur2 report? RMarkdown. The latest pdf Alyanne had to send to an ethical committee? Again RMarkdown.

These websites are examples too: click, click.

Have a look around on the following website to get a feeling for what is possible with Rmarkdown.

The options include:

  • documents
    • pdf
    • Word
    • html (also: blogs)
    • handouts
    • books
  • interactive documents
    • html widgets
    • dashboards
    • shiny applications
  • presentations
    • slides (Beamer, ioslides, Slidy etc)
    • Powerpoint presentation

8.3.1 Setting output format

You can specifically choose which output format to render to with the RStudio “Knit” button in the toolbar, or with:

rmarkdown::render("your_file_name.Rmd", output_format = "word_document")

But usually, you use the YAML header to control which output format(s) knitting will produce and even customize the options for each format separately. To customize each output format, you can alter the YAML header output argument:

---
title: "My document"
output:
  html_document:
---

You can change html_document to for instance pdf_document or word_document.

Or customize HTML and PDF output both, this is useful if you want to render multiple types of output.:

---
title: "My document"
output:
  html_document:
    toc: true
    toc_float: true
  pdf_document:
    fig_caption: false
---
Exercise 8

This exercise is adapted from this one from r4ds here

Copy and paste the contents of Lorem.Rmd here to a .Rmd file.

From this .Rmd, knit one new document for each of the three built-in formats: HTML, PDF and Word. How does the output differ? How does the input differ? (You may need to install LaTeX in order to build the PDF output — RStudio will prompt you if this is necessary.)

8.3.2 Output options

The YAML header can contain a lot more settings for your output. For instance, you may want to add a table of contents (TOC) to you html page, in this example a floating one:

---
title: "My document"
output:
  html_document:
    toc: true
    toc_float: true
---

Other settings can just be added below html_document:

Tabbed sections

You can organize content using tabs by applying the .tabset class attribute to headers within a document. This will cause all sub-headers of the header with the .tabset attribute to appear within tabs rather than as standalone sections. For example:

## Quarterly Results {.tabset}

### By Product

(tab content)

### By Region

(tab content)

Themes

You learned how to specify you own formatting with css last lesson. But RMarkdown has some preset themes you can use as well. And of course, you can download packages with more themes.

---
title: "Stuff"
output:
  html_document:
    theme: united
---
Exercise 8
  1. What is a floating TOC?
  2. Use Lorem.Rmd again and add a TOC
  3. Give the TOC a set depth (toc_depth) and see what happens if you change it. (for instance toc_depth: 2 can be set just as you set toc_float: true earlier.)
  4. Also try code_folding: hide and number_sections: FALSE.
  5. Google how to put two authors on one .Rmd, with affiliations. Put your and your labpartner’s names as authors.
  6. Apply a theme you like, but not “united”.
  7. try tabbed sections

8.4 PDF

Rendering pdf files does not differ much from html. Themes work as well. There are few things you can set in the YAML header for pdf files. Note that these options do not get an indent, but rather need to be defined at the same level as title, author, output etc.

---
title: "My document"
output: pdf_document
fontsize: 11pt
geometry: margin=1in
---

8.5 Word …

Now word files are a different beast… You can export them easily enough:

---
title: "My weekly report"
author: Joep
date: March 22, 1999
output: word_document
---

But now how do we edit the layout? RMarkdown can use a reference .docx file to get all the layout information from.

Exercise 8

8.6 Interactivity

Until now, we discussed static output formats. But RMarkdown files can also render interactive content! There are two main types of content to render: html widgets and shiny apps. Shiny apps will be covered in two masterclasses in the projecticum. Shiny uses actual R code to render the interactivity. This gives you a very broad range of options, but also means that it requires a live R session running somewhere.

HTML widgets use JavaScript libraries to produce for instance interactive graphs, using R syntax! These will work without an R session, in any web browser.They will still only work in html though, you can’t suddenly make pdf files interactive.

8.6.1 Tables

We actually already showed you how to make interactive tables with datatable() in a previous lesson:

library(DT)
datatable(iris, options = list(pageLength = 5))

8.6.2 Javascript packages

You can do similar interactivity with graphs and figures. Generally, these packages link R to a javascript packages. Check the possibilities here. These packages actually do most of the work for you.

Let’s try a few:

Maps

The leaflet package let’s you use maps (click on the dot and try moving the map)

library(htmlwidgets)
library(leaflet)

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lat=52.084036170323024, lng=5.173630727235891, popup="Here be HL7!") 
# get coordinates from google maps

m  # Print the map

Figure 1.2: You are here! But not in 2021, in 2021 we are at home

Suppose you want to show all locations where you catched rabbits for your ongoing study on rabbit ear length at the Uithof:

library(leaflet)
library(tidyverse)

rabbit_locations <- tibble( rabbitnr = c(1:5),
                            lat  = c(52.0852,52.0832,52.08247,52.0834,52.08309),
                            long = c(5.171109,5.171248,5.171248,5.176055,5.17268) )

leaflet(data = rabbit_locations) %>% addTiles() %>% 
  addMarkers(~long, ~lat, popup = ~as.character(rabbitnr), label = ~as.character(rabbitnr))

Figure 2.1: Here be rabbits

Want more? Check out this website here

Exercise 8

rabbits!

Change the markers in the example above to little icons of rabbits! See here (click) how to do this.

3d figures

Sometimes 2 axes don’t cut it.

library(threejs)
library(palmerpenguins)
z <- penguins$bill_length_mm
x <- penguins$flipper_length_mm
y <- penguins$body_mass_g
N = length(levels(penguins$species)) # we want 3 colours
scatterplot3js(x,y,z, color=rainbow(N)[penguins$species])

Figure 1.3: With 3 axes you may want to be able to rotate the graph.

See some more examples, if you like, here: click

Time series

This rabbit ear experiment has been going for quite a while. Let’s say you started catching rabbits about 10 years ago and calculated average ear length every three weeks. The graph below shows the average ear length per 3 weeks. It also shows the time frame of the mysterious long ear disease (LED) outbreak of 2018:

# Libraries
library(dygraphs)
library(xts) 

# get some data
# Your time column MUST be a time format or numbers
rabbitdata <- data.frame(
  time=seq(from=Sys.Date()-(10*365), to=Sys.Date(), by=21 ), 
  oorlengte=runif((10*365)/21+1,min = 6, max = 10)
)

rabbitdata$oorlengte[120:138]<-rabbitdata$oorlengte[120:138]+4

# create xts format because dygraph() only eats xts
rabbitdata.xts <- xts(x = rabbitdata$oorlengte, order.by = rabbitdata$time)

# plot
dygraph(rabbitdata.xts) %>% 
  dySeries(label="average ear length (cm)", color="black") %>%
  dyShading(from=rabbitdata$time[120], to=rabbitdata$time[138], color="#FFE6E6") %>%
  dyRangeSelector(dateWindow = c(rabbitdata$time[90], rabbitdata$time[150]))

Figure 1.4: Average rabbit ear length at the uithof per 3 weeks for the last 10 years.

See some more examples, if you like, here: click

Plotly

And most famously, plotly. This package can turn any ggplot2 graph into an interactive plotly graph. Mousing over a point displays information about that point. Clicking on a legend point removes that class from the plot. Clicking on it again returns it.

Plotly can just make your scatterplot zoom-able with labels for the data points:

library(plotly)

fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)

fig

Figure 1.5: Minimal example plotly graph

#box plots
plot_ly(                  #creates first box plot
  y = rnorm(50),          #choose numeric variable for first plot
  type = "box") %>%       #specifies plot type is box plot
  
  add_trace(              #creates second box plot
    y = rnorm(50, 1))     #choose numeric variable for second plot

Basically, if you think “Hey, I have this ggplot graph and it is nice, but it could be clearer if it had some interactive options…” take a look at the plotly examples here. It is also rather useful when you want subplots in your figure, like this:

library(plotly)
fig1 <- plot_ly(economics, x = ~date, y = ~unemploy)
fig1 <- fig1 %>% add_lines(name = ~"unemploy")
fig2 <- plot_ly(economics, x = ~date, y = ~uempmed)
fig2 <- fig2 %>% add_lines(name = ~"uempmed")
fig <- subplot(fig1, fig2)

fig

Figure 2.2: Plotly with subplots. You can also use cowplot()

It can do Sankey diagrams. Sankey diagrams are what the cool kids do nowadays, it seems. A Sankey Diagram is a visualisation technique that allows to display flows.

fig <- plot_ly(
    type = "sankey",
    orientation = "h",

    node = list(
      label = c("A1", "A2", "B1", "B2", "C1", "C2"),
      color = c("blue", "blue", "purple", "purple", "darkred", "darkred"),
      pad = 15,
      thickness = 20,
      line = list(
        color = "black",
        width = 0.5
      )
    ),

    link = list(
      source = c(0,1,0,2,3,3),
      target = c(2,3,3,4,4,5),
      value =  c(8,4,2,8,4,2)
    )
  )
fig <- fig %>% layout(
    title = "Basic Sankey Diagram",
    font = list(
      size = 10
    )
)

fig

Figure 2.3: Sankey diagram


CC BY-NC-SA 4.0 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Unless it was borrowed (there will be a link), in which case, please use their license.