webR/WebAssembly Demo

Author

Jeffrey M. Perkel

Published

April 5, 2024

webR and WebAssembly

This document demonstrates the webR package for the #rstats community. Using it, in conjunction with the quarto-webr Quarto extension, users can create Quarto documents that allow readers to explore their code and data.

In a traditional executable manuscript, results are calculated and figures generated when the document is compiled. This promotes accuracy and reproducibility, but the resulting document is static – readers cannot, for instance, plug in different numbers to test a model’s robustness.

Using webR and quarto-webr, however, you can create web pages in which the code is executed on demand, in the web browser. Among other things, this allows researchers to create tools so others may explore their data.

Key to these tools is WebAssembly, a system for executing code written in such languages as C, C++ and Rust, in the browser. When a WebAssembly-enabled page is accessed, the code is downloaded and executed in a sandboxed virtual machine inside the browser itself – no installation required.

webR is a port of the R interpreter to WebAssembly, and quarto-webr is an extension to the Quarto system that allows users to embed webR code cells into their Quarto documents. Together, they allow us to create a document that allows users to modify and execute R code on demand.

Graphing a line

We’ll demonstrate these possibilities using the equation for a line, \[y = mx + b\] By changing the values for slope (m) and y-intercept (b), we can see how the line changes.

  1. Click the Run Code button to draw the line y = x.
  2. Adjust the values of b and m below to specify a new line.
  3. Click Run Code to see how the line changes.

Explore

In the cell below, feel free to explore. For instance, you might give our plot from the previous cell (stored in the object p) a title. Type p + labs(title = "Graph of a line") and click Run Code.

Or, feel free to explore the standard automotive dataset mtcars. Take a peek at the dataset with glimpse(mtcars). And view the relationship between automobile weight and fuel efficiency with:

mtcars |> 
  mutate(cyl = factor(cyl)) |> 
  ggplot(aes(x = mpg, y = wt, color = cyl)) + 
  geom_point() + 
  theme_minimal()

GitHub repo

Click here for the GitHub repository that contains the code for this document.