Load packages needed for this session.

library(kableExtra)
library(DT)
library(ggplot2)
library(dplyr)
library(highcharter)
library(plotly)
library(ggiraph)
library(dygraphs)
library(networkD3)
library(leaflet)
library(crosstalk)

All formatting covered under markdown is also applicable here.

1 Executed code

Code can be executed during document render. Code can be rendered in inline (within a sentence) or in code chunks (code blocks).

R code can be executed inline line this `r Sys.Date()` producing 2021-04-28.

R code can be executed inside code chunks like this

```{r}
Sys.Date()
``` 

which shows the code and output.

Sys.Date()
## [1] "2021-04-28"

Arguments/Parameters to the code chunks are specified inside the {}. The first argument is the engine used to evaluate the code chunk. Here we mostly use r. Other options such as python, bash etc can be used. Code chunks can take many more optional arguments.

The code and results can be hidden by ```{r,echo=FALSE,results='hide'}`.

Here is another example of executed R code with input and output.

data(iris)
head(iris[,1:2])
##   Sepal.Length Sepal.Width
## 1          5.1         3.5
## 2          4.9         3.0
## 3          4.7         3.2
## 4          4.6         3.1
## 5          5.0         3.6
## 6          5.4         3.9

All chunks options are listed here.

The default code when executed shows input code and output results.

```{r}
Sys.Date()
``` 
Sys.Date()
## [1] "2021-04-28"

Input code can be hidden.

```{r,echo=FALSE}
Sys.Date()
``` 
## [1] "2021-04-28"

Output results can be hidden

```{r,results='hide'}
Sys.Date()
``` 
Sys.Date()

The code can be displayed with code highlighting but not executed.

```{r,eval=FALSE}
Sys.Date()
``` 
Sys.Date()

2 Images

2.1 Using R

R chunks in RMarkdown can be used to control image display size using the arguemnt out.width.

This image below is displayed at a size of 300 pixels.

```{r,out.width=300}
knitr::include_graphics('assets/cover.jpg')
``` 

This image below is displayed at a size of 75 pixels.

```{r,out.width=75}
knitr::include_graphics('assets/cover.jpg')
``` 

3 Math expressions

Some examples of rendering equations.

$e^{i\pi} + 1 = 0$

\(e^{i\pi} + 1 = 0\)

$$\frac{E \times X^2 \prod I}{2+7} = 432$$

\[\frac{E \times X^2 \prod I}{2+7} = 432\]

$$\sum_{i=1}^n X_i$$

\[\sum_{i=1}^n X_i\]

$$\int_0^{2\pi} \sin x~dx$$

\[\int_0^{2\pi} \sin x~dx\]

$\left( \sum_{i=1}^{n}{i} \right)^2 = \left( \frac{n(n-1)}{2}\right)^2 = \frac{n^2(n-1)^2}{4}$

\(\left( \sum_{i=1}^{n}{i} \right)^2 = \left( \frac{n(n-1)}{2}\right)^2 = \frac{n^2(n-1)^2}{4}\)

$\begin{eqnarray} X & \sim & \mathrm{N}(0,1)\\ Y & \sim & \chi^2_{n-p}\\ R & \equiv & X/Y \sim t_{n-p} \end{eqnarray}$

\(\begin{eqnarray} X & \sim & \mathrm{N}(0,1)\\ Y & \sim & \chi^2_{n-p}\\ R & \equiv & X/Y \sim t_{n-p} \end{eqnarray}\)

$\begin{eqnarray} P(|X-\mu| > k) & = & P(|X-\mu|^2 > k^2)\\ & \leq & \frac{\mathbb{E}\left[|X-\mu|^2\right]}{k^2}\\ & \leq & \frac{\mathrm{Var}[X]}{k^2} \end{eqnarray}$

\(\begin{eqnarray} P(|X-\mu| > k) & = & P(|X-\mu|^2 > k^2)\\ & \leq & \frac{\mathbb{E}\left[|X-\mu|^2\right]}{k^2}\\ & \leq & \frac{\mathrm{Var}[X]}{k^2} \end{eqnarray}\)

4 Tables

4.1 Paged

View of the data using paged tables. This is the default output for RMarkdown.

Tab. 1: Table using paged tibble.

iris[1:15,]
##    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1           5.1         3.5          1.4         0.2  setosa
## 2           4.9         3.0          1.4         0.2  setosa
## 3           4.7         3.2          1.3         0.2  setosa
## 4           4.6         3.1          1.5         0.2  setosa
## 5           5.0         3.6          1.4         0.2  setosa
## 6           5.4         3.9          1.7         0.4  setosa
## 7           4.6         3.4          1.4         0.3  setosa
## 8           5.0         3.4          1.5         0.2  setosa
## 9           4.4         2.9          1.4         0.2  setosa
## 10          4.9         3.1          1.5         0.1  setosa
## 11          5.4         3.7          1.5         0.2  setosa
## 12          4.8         3.4          1.6         0.2  setosa
## 13          4.8         3.0          1.4         0.1  setosa
## 14          4.3         3.0          1.1         0.1  setosa
## 15          5.8         4.0          1.2         0.2  setosa

4.2 kable

The most simple table using kable from R package knitr.

knitr::kable(head(iris), 'html')
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa

4.3 kableExtra

More advanced table using kableExtra and formattable.

Tab. 2: Table using kableextra.

 iris[c(1:4,51:53,105:108),] %>%
  mutate(Sepal.Length=color_bar("lightsteelblue")(Sepal.Length)) %>%
  mutate(Sepal.Width=color_tile("white","orange")(Sepal.Width)) %>%
  mutate(Species=cell_spec(Species,"html",color="white",bold=T,
    background=c("#8dd3c7","#fb8072","#bebada")[factor(.$Species)])) %>%
  kable("html",escape=F) %>%
  kable_styling(bootstrap_options=c("striped","hover","responsive"),
                full_width=F,position="left") %>%
  column_spec(5,width="3cm")
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
51 7.0 3.2 4.7 1.4 versicolor
52 6.4 3.2 4.5 1.5 versicolor
53 6.9 3.1 4.9 1.5 versicolor
105 6.5 3.0 5.8 2.2 virginica
106 7.6 3.0 6.6 2.1 virginica
107 4.9 2.5 4.5 1.7 virginica
108 7.3 2.9 6.3 1.8 virginica

4.4 DT

Interactive table using R package DT.

Tab. 3: Table using datatable.

iris %>%
  slice(1:15) %>%
  datatable(options=list(pageLength=7))

5 Static plots

5.1 Base plot

  • Plots using base R are widely used and may be good enough for most situations.
  • But they lack a consistent coding framework.
{plot(x=iris$Sepal.Length,y=iris$Sepal.Width,
      col=c("coral","steelblue","forestgreen")[iris$Species],
      xlab="Sepal Length",ylab="Sepal Width",pch=19)
legend(x=7,y=4.47,legend=c("setosa","versicolor","virginica"),
       col=c("coral","steelblue","forestgreen"),pch=19)}

Fig. 1: Static plot using base plot.

5.2 ggplot2

R package ggplot2 is one of the most versatile and complete plotting solutions.

iris %>%
  ggplot(aes(x=Sepal.Length,y=Sepal.Width,col=Species))+
  geom_point(size=2)+
  labs(x="Sepal Length",y="Sepal Width")

Fig. 2: Static plot using ggplot2.

6 Interactive plots

6.1 highcharter

R package highcharter is a wrapper around javascript library highcharts.

h <- iris %>%
  hchart(.,"scatter",hcaes(x="Sepal.Length",y="Sepal.Width",group="Species")) %>%
  hc_xAxis(title=list(text="Sepal Length"),crosshair=TRUE) %>%
  hc_yAxis(title=list(text="Sepal Width"),crosshair=TRUE) %>%
  hc_chart(zoomType="xy",inverted=FALSE) %>%
  hc_legend(verticalAlign="top",align="right") %>%
  hc_size(height=400)

htmltools::tagList(list(h))

Fig. 3: Interactive scatterplot using highcharter.

6.2 plotly

R package plotly provides R binding around javascript plotting library plotly.

p <- iris %>% 
  plot_ly(x=~Sepal.Length,y=~Sepal.Width,color=~Species,width=500,height=400) %>% 
  add_markers()
p

Fig. 4: Interactive scatterplot using plotly.

6.3 ggplotly

plotly also has a function called ggplotly which converts a static ggplot2 object into an interactive plot.

p <- iris %>%
  ggplot(aes(x=Sepal.Length,y=Sepal.Width,col=Species))+
  geom_point()+
  labs(x="Sepal Length",y="Sepal Width")+
  theme_bw(base_size=12)

ggplotly(p,width=500,height=400)

Fig. 5: Interactive scatterplot using ggplotly.

6.4 ggiraph

ggiraph is also an R package that can be used to convert a static ggplot2 object into an interactive plot.

p <- ggplot(iris,aes(x=Sepal.Length,y=Petal.Length,colour=Species))+
      geom_point_interactive(aes(tooltip=paste0("<b>Petal Length:</b> ",Petal.Length,"\n<b>Sepal Length: </b>",Sepal.Length,"\n<b>Species: </b>",Species)),size=2)+
  theme_bw()

tooltip_css <- "background-color:#e7eef3;font-family:Roboto;padding:10px;border-style:solid;border-width:2px;border-color:#125687;border-radius:5px;"

ggiraph(code=print(p),hover_css="cursor:pointer;stroke:black;fill-opacity:0.3",zoom_max=5,tooltip_extra_css=tooltip_css,tooltip_opacity=0.9)

Fig. 6: Interactive scatterplot using ggiraph.

6.5 dygraphs

R package dygraphs provides R bindings for javascript library dygraphs for time series data.

lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
dygraph(lungDeaths,main="Deaths from Lung Disease (UK)") %>%
  dyOptions(colors=c("#66C2A5","#FC8D62","#8DA0CB"))

Fig. 7: Interactive time series plot using dygraph.

6.6 Network graph

R package networkD3 allows the use of interactive network graphs from the D3.js javascript library.

data(MisLinks,MisNodes)
forceNetwork(Links=MisLinks,Nodes=MisNodes,Source="source",
             Target="target",Value="value",NodeID="name",
             Group="group",opacity=0.4)

Fig. 8: Interactive network plot.

6.7 leaflet

R package leaflet provides R bindings for javascript mapping library; leafletjs.

leaflet(height=500,width=700) %>% 
  addTiles(urlTemplate='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') %>%
  #addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
  addMarkers(lat=57.639327,lng=18.288534,popup="RaukR") %>%
  setView(lat=57.639327,lng=18.288534,zoom=15)

Fig. 9: Interactive map using leaflet.

6.8 crosstalk

R package crosstalk allows crosstalk enabled plotting libraries to be linked. Through the shared ‘key’ variable, data points can be manipulated simultaneously on two independent plots.

shared_quakes <- SharedData$new(quakes[sample(nrow(quakes), 100),])
lf <- leaflet(shared_quakes,height=300) %>%
        addTiles(urlTemplate='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') %>%
        addMarkers()
py <- plot_ly(shared_quakes,x=~depth,y=~mag,size=~stations,height=300) %>% 
        add_markers()

htmltools::div(lf,py)

Fig. 10: Linking independent plots using crosstalk.