les <- 8 knitr::opts_chunk$set(echo = TRUE, class.source="Rchunk", class.output="Rout")
After this lesson you will be able to
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
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:
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 ---
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:
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)
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 ---
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 ---
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.
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.
We actually already showed you how to make interactive tables with datatable()
in a previous lesson:
library(DT) datatable(iris, options = list(pageLength = 5))
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:
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
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))
Want more? Check out this website here
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])
See some more examples, if you like, here: click
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]))
See some more examples, if you like, here: click
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
#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
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
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.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.