Interactive R with RMarkdown

This document demonstrates how to use various R packages to add interactivity and utilize different programming languages within RStudio. You’ll learn about popular packages like leaflet and plotly, which enable interactive data visualizations, as well as how to incorporate languages like Python, C++, and Bash directly into RMarkdown.

For source code see github page.

Package Setup

lop <- c("reticulate", "Rcpp", "leaflet", "ggplot2", "plotly", "visNetwork", "DT")

to_instal <- lop[which(x = !lop %in% installed.packages()[,"Package"])]

if(length(x = to_instal) != 0) {
  install.packages(pkgs = to_instal)
}

aux <- lapply(X = lop, FUN = library, character.only = TRUE)

rm(list = c("lop", "to_instal", "aux"))
gc()
##           used  (Mb) gc trigger  (Mb) max used  (Mb)
## Ncells 1973832 105.5    3890660 207.8  2661311 142.2
## Vcells 3400746  26.0    8388608  64.0  4806098  36.7

This code block installs and loads a set of essential packages used in this document. Here’s a quick overview of each:

  • reticulate: Integrates Python into R, allowing you to run Python code in R scripts.
  • Rcpp: Links R with C++ code, enabling high-performance computation.
  • leaflet: Used for creating interactive maps.
  • ggplot2: A powerful data visualization package.
  • plotly: Provides interactive plots and works seamlessly with ggplot2.
  • visNetwork: Allows creation of network visualizations.
  • DT: Displays data tables with interactive features.

Integrating Other Languages in RStudio

RStudio supports multi-language workflows, letting you run code in Python, C++, and Bash within an RMarkdown file.

Python

Using the reticulate package, we can run Python code in RStudio.

Example: Using Python Variables in R

In this example, we create a variable in Python and access it from R.

x = .1 + .1 + .1
print(x)
## 0.30000000000000004
py$x
## [1] 0.3

Example: Using R Variables in Python

Similarly, we can define a variable in R and access it in Python.

x <- rnorm(n = 10)
print(r.x)
## [-0.9716642619059848, -1.2537200556172345, 0.40997290865026154, 0.9794892034230105, 1.293607471665794, 2.1111744801577332, 0.08063494948001483, -0.8390692946026795, -1.075719032876108, -1.1267352860592397]

C++

With the Rcpp package, we can write C++ code directly in RMarkdown. Here’s a simple example function written in C++ to double each element of a vector.

#include <Rcpp.h>

//[[Rcpp::export]]
Rcpp::IntegerVector add_number(Rcpp::IntegerVector x) {
  return x + x;
}

We can call this function in R:

add_number(c(2, 184))
## [1]   4 368

Bash

Bash commands can be executed in RMarkdown, making it easy to interact with the command line. For more Bash examples, see this link.

echo "Hello Bash!"
ls -la
## Hello Bash!
## total 6525
## drwxr-xr-x 1 42073 42073       0 Nov  6 17:05 .
## drwxr-xr-x 1 42073 42073       0 Nov  6 17:05 ..
## -rw-r--r-- 1 42073 42073    1535 Nov  6 17:05 01_data_import.R
## -rw-r--r-- 1 42073 42073    2094 Nov  6 17:05 02_datatable.R
## -rw-r--r-- 1 42073 42073    3436 Nov  6 17:05 03_ggplot2.R
## -rw-r--r-- 1 42073 42073    6698 Nov  6 17:09 04_markdown.Rmd
## -rw-r--r-- 1 42073 42073 6647967 Nov  6 17:05 04_markdown.html
## -rw-r--r-- 1 42073 42073     164 Nov  6 17:05 XX_usethis.R
## drwxr-xr-x 1 42073 42073       0 Nov  6 17:05 rsconnect

Interactive HTML Widgets

HTML widgets in R enable interactive data visualizations directly within RMarkdown.

Leaflet: Interactive Maps

leaflet is a powerful package for creating interactive maps in R. In this example, we use earthquake data (quakes) and map the locations with markers.

data(quakes)
head(quakes)
##      lat   long depth mag stations
## 1 -20.42 181.62   562 4.8       41
## 2 -20.62 181.03   650 4.2       15
## 3 -26.00 184.10    42 5.4       43
## 4 -17.97 181.66   626 4.1       19
## 5 -20.42 181.96   649 4.0       11
## 6 -19.68 184.31   195 4.0       12
leaflet(data = quakes[1:20,]) %>%
  addTiles() %>%
  addMarkers(lng = ~long, lat = ~lat, popup = ~as.character(x = mag), label = ~as.character(x = mag))

Plotly: Interactive Graphs

The plotly package allows you to create interactive plots. It integrates well with ggplot2, allowing static ggplot objects to be made interactive.

ggplot2 with Plotly

Here’s a bar plot of diamond cuts by clarity, enhanced with plotly.

p <- ggplot(data = diamonds, mapping = aes(x = cut, fill = clarity)) +
            geom_bar(position = "dodge")

ggplotly(p = p)

Pure Plotly

You can also use plotly directly without ggplot2 for custom visualizations.

plot_ly(z = ~volcano, type = "heatmap")
plot_ly(z = ~volcano, type = "surface")

visNetwork: Network Visualizations

The visNetwork package enables interactive network visualization in R.

nodes <- data.frame(id = 1:6, title = paste("node", 1:6), shape = c("dot", "square"), size = 10:15, color = c("blue", "red"))
edges <- data.frame(from = 1:5, to = c(5, 4, 6, 3, 3))
head(x = nodes)
##   id  title  shape size color
## 1  1 node 1    dot   10  blue
## 2  2 node 2 square   11   red
## 3  3 node 3    dot   12  blue
## 4  4 node 4 square   13   red
## 5  5 node 5    dot   14  blue
## 6  6 node 6 square   15   red
visNetwork(nodes = nodes, edges = edges)

The following example demonstrates customization with different node shapes, colors, and interactive options:

nodes <- data.frame(id = 1:10, 
                    label = paste("Node", 1:10),
                    group = c("GrA", "GrB"),
                    value = 1:10, 
                    shape = c("square", "triangle", "box", "circle", "dot", "star",
                              "ellipse", "database", "text", "diamond"),
                    title = paste0("<p><b>", 1:10,"</b><br>Node !</p>"), 
                    color = c("darkred", "grey", "orange", "darkblue", "purple"),
                    shadow = c(FALSE, TRUE, FALSE, TRUE, TRUE)) 

edges <- data.frame(from = sample(1:10,8), to = sample(1:10, 8),
                    label = paste("Edge", 1:8), 
                    length = c(100,500), 
                    arrows = c("to", "from", "middle", "middle;to"),
                    dashes = c(TRUE, FALSE),  
                    title = paste("Edge", 1:8), 
                    smooth = c(FALSE, TRUE),  
                    shadow = c(FALSE, TRUE, FALSE, TRUE)) 

visNetwork(nodes = nodes, edges = edges) %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)

DataTables: Interactive Data Tables

The DT package renders interactive tables. Here, we display the iris dataset in a searchable and sortable format.

datatable(data = iris, options = list(pageLength = 10), class = "cell-border stripe", editable = "cell")

\(\LaTeX\): Mathematical Expressions

In RMarkdown, you can use LaTeX to format mathematical expressions. Here’s the formula for the three-parameter Generalized Pareto distribution (GPD):

\[ f(x) = \alpha^{-1}e^{-(1 - \kappa)y}, \quad y = \begin{cases} -\kappa^{-1}\log \Big[ 1 - \frac{\kappa(x - \xi)}{\alpha} \Big], & \kappa \neq 0,\\ \frac{(x - \xi)}{\alpha}, & \kappa = 0. \end{cases} \]

where: - \(\xi\): location parameter - \(\alpha > 0\): scale parameter - \(\kappa\): shape parameter, affecting the range of \(x\).

This setup provides a flexible base for using RMarkdown to demonstrate code, visualizations, and interactivity.