R Environment

Default environments for R 3.6.

This notebook describes and creates the default R environment in Nextjournal. Check out the showcase if you want to see what the environment contains. To see how it’s built, see setup.

Showcase

These packages are included in Nextjournal's R 3.6 environment.

suppressMessages(library(dplyr))
installed.packages() %>%
  as_tibble() %>%
  select(Package, Version) %>%
  arrange(Package)
0.9s
Showcase (R)
R
0 items

System Packages and Basics

A number of support libraries are installed, as well as gcc v7 for installing Rcpp and other packages that require compilation.

The Rcpp package version

nil
allows for tight integration between R and C++ codes and libraries. The Tidyverse is also installed—this is a set of several data science packages which all follow certain design, grammar, and structural characteristics.

R packages are installed using install.packages() or devtools::install_github() in an R cell. Please refer to the R section of Installing Software and Packages for more detailed information.

Plotting

Three plotting methods are available in the default environment. The built-in R plotting system works automatically to create static plots, Plotly v

nil
provides full access to the functionality of Plotly on R to generate figures with basic interactivity, and ggplot2 v
nil
syntax can be used either statically or with Plotly's ggplotly() function, which will add some interactivity.

R

x <- seq(-10, 10, length= 60); y <- x
f <- function(x, y) { r <- sqrt(x^2+y^2); sin(r)/r }
z <- outer(x, y, f)
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "#009caa"); NULL
0.5s
Showcase (R)
R

Plotly

This syntax allows full access to the functionality of Plotly on R.

library(plotly)
d <- diamonds[sample(nrow(diamonds), 1000), ]
plot_ly(d, x = ~carat, y = ~price,
  # Hover text:
  text = ~paste("Price: ", price, '$<br>Cut:', cut),
  color = ~carat, size = ~carat, type='scatter', mode='markers')
1.0s
Showcase (R)
R
Loading viewer…

ggplot2

Plot with the ggplot2 package.

library(ggplot2)
qplot(speed, dist, data=cars) + geom_smooth()
0.5s
Showcase (R)
R

Data Structures

In addition to standard R functionality, Nextjournal's default R environment contains several packages for data manipulation and parsing.

Data Frames

The standard R data structure is the data.frame. This is a table with named columns, numbered rows, and can have columns with enumerated factors. Nextjournal will automatically attempt to display a data frame when it is the final return value of a cell.

iris
0.3s
Showcase (R)
R
0 items

Tibbles

One of the many packages from the Tidyverse provides tibbles: a modification of data frames that are lazy (do not modify input data) and surly (complain more about errors). Any data.frame object can easily be converted to a tibble, and will display in much the same way:

library(tibble)
as_tibble(mtcars)
0.3s
Showcase (R)
R
0 items

JSONlite

The jsonlite package provides simple (de)serialization functions.

toJSON(iris, pretty=TRUE)
0.4s
Showcase (R)
R

Setup

The full setup starting from a minimal Ubuntu installation is below

Build a Minimal R Environment

Install R from the R 3.5/3.6 repository for Ubuntu. The build-essential package (which includes gcc) is a necessary prerequisite for installation of some R packages.

echo 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/' > \
  /etc/apt/sources.list.d/r35.list
key_id=`curl -s https://cloud.r-project.org/bin/linux/ubuntu/README \
  | grep "sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys" \
  | sed 's/.* //'`
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys $key_id
apt-get -qq update
DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends \
  r-base
apt-get clean
rm -r /var/lib/apt/lists/* # Clear package list so it isn't stale
23.6s
Minimal R (Bash)

Setup package install options.

echo 'local({
  r <- getOption("repos")
  r["CRAN"] <- "https://cloud.r-project.org"
  options(repos = r, download.file.method = "libcurl")
})' > /etc/R/Rprofile.site
0.1s
Minimal R (Bash)

Install two necessary packages for R to work on Nextjournal.

R -e 'install.packages(c("base64enc", "jsonlite"), Ncpus=4)'
8.6s
Minimal R (Bash)

Build the Default R Environment

Install

Install libraries that R needs for compilation of packages.

apt-get -qq update
DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends \
  libssh2-1 libcurl4-openssl-dev libssl-dev libxml2-dev \
  r-base-dev libcairo2-dev libpango1.0-dev libpangocairo-1.0
apt-get clean
rm -r /var/lib/apt/lists/*
20.1s
R (Bash in R)
Minimal R

Install the conda Jupyter package, then ensure jupyter-client and jupyter-core are the latest releases. Jupyter-core devel used to address connection file permissions issue, revert when 4.6.2 is released. —MPD 15 Dec 2019

conda install jupyter
conda clean -qtipy
pip install --upgrade jupyter-client \
  git+https://github.com/jupyter/jupyter_core
26.4s
R (Bash in R)
Minimal R

This default image has support for tidyverse, plotly, svglite, and shiny. The package also makes some basic utilities available, as well as devtools to help facilitate the use of certain packages, and packrat and renv for installations. Remaining packages are installed to support the Jupyter IRkernel.

install.packages(c("devtools", "remotes", "packrat", "renv", 
                   "tidyverse", "uuid", "digest", 
                   "plotly", "svglite", "shiny",
                   "feather", "arrow", "R.matlab", "repr", "future", "evaluate", 
                   "pbdZMQ", "crayon", "IRdisplay", "IRkernel"), 
                 Ncpus=4)
IRkernel::installspec()
798.2s
R (R)
Minimal R

Setup default fonts for built-in plots, and when ggplot2 and/or svglite are loaded. This .Rprofile will be mounted to root's home directory, and saved with the environment.

local({
  if (file.exists("/usr/share/fonts/truetype/Fira_Sans") || 
      file.exists("/usr/share/fonts/truetype/dejavu")) {
    fonts <- "Fira Sans,PT Sans,Open Sans,DejaVu Sans,sans-serif"
  } else {
    fonts <- "sans"
  }
  options(nextjournal.svg.device.default.fonts = fonts)
})
setHook(packageEvent("ggplot2", "onLoad"), 
  function(pkgname,pkgpath) {
    if (file.exists("/usr/share/fonts/truetype/Fira_Sans") || 
        file.exists("/usr/share/fonts/truetype/dejavu")) {
      fonts <- "Fira Sans,PT Sans,Open Sans,DejaVu Sans,sans-serif"
    } else {
      fonts <- "sans"
    }
    options(nextjournal.ggplot.device.default.fonts = fonts)
    ggplot2::theme_update(text = ggplot2::element_text(family = fonts))
  })
setHook(packageEvent("svglite", "onLoad"), 
  function(pkgname,pkgpath) {
    # Function to build a font alias with all four standard faces, 
    # needed because font filenames are not standardized.
    faces <- function(fam,base,r,i,b,bi) {
      list(plain = list(alias = fam, file = paste0(base,r)),
          italic = list(alias = fam, file = paste0(base,i)),
            bold = list(alias = fam, file = paste0(base,b)),
      bolditalic = list(alias = fam, file = paste0(base,bi)))
    }
    if (file.exists("/usr/share/fonts/truetype/Fira_Sans") && 
        file.exists("/usr/share/fonts/truetype/PT_Serif")) {
      fonts <- list(
        sans = faces("Fira Sans,PT Sans,Open Sans,DejaVu Sans,sans-serif",
                     "/usr/share/fonts/truetype/Fira_Sans/FiraSans-",
                     "Regular.ttf","Italic.ttf",
                     "Bold.ttf","BoldItalic.ttf"),
       serif = faces("PT Serif,Noto Serif,DejaVu Serif,serif",
                     "/usr/share/fonts/truetype/PT_Serif/PT_Serif-Web-",
                     "Regular.ttf","Italic.ttf",
                     "Bold.ttf","BoldItalic.ttf"))
    } else { # Fallback for older environments which only had DejaVu fonts
      fonts <- list(
        sans = faces("DejaVu Sans,Fira Sans,PT Sans,Open Sans,sans-serif",
                     "/usr/share/fonts/truetype/dejavu/DejaVuSans",
                     ".ttf","-Oblique.ttf",
                     "-Bold.ttf","-BoldOblique.ttf"),
       serif = faces("DejaVu Serif,PT Serif,Noto Serif,serif",
                    "/usr/share/fonts/truetype/dejavu/DejaVuSerif",
                    ".ttf","-Italic.ttf",
                     "-Bold.ttf","-BoldItalic.ttf"))
    }
    options(nextjournal.svglite.device.default.fonts = fonts)
  })
.Rprofile
R

Cleanup.

rm -rf /tmp/*
0.1s
R (Bash in R)
Minimal R

Checks.

du -hsx /
jupyter kernelspec list
2.3s
R (Bash in R)
Minimal R

Test

strsplit(R.version.string," ")[[1]][[3]]
0.6s
R versionShowcase (R)
R
jupyter kernelspec list
jupyter --version
jupyter --paths
cat /usr/local/share/jupyter/kernels/ir/kernel.json
cp /usr/local/share/jupyter/kernels/ir/logo-64x64.png /results/logo.png
1.6s
Showcase (Bash in R)
R
packageDescription("Rcpp")[["Version"]]
0.7s
Rcpp versionShowcase (R)
R
packageDescription("tidyverse")[["Version"]]
0.7s
tidyverse versionShowcase (R)
R
packageDescription("plotly")[["Version"]]
0.7s
Plotly versionShowcase (R)
R
packageDescription("ggplot2")[["Version"]]
0.7s
ggplot2 versionShowcase (R)
R
packageDescription("jsonlite")[["Version"]]
0.7s
jsonlite versionShowcase (R)
R
packageDescription("svglite")[["Version"]]
0.7s
svglite versionShowcase (R)
R
packageDescription("feather")[["Version"]]
0.7s
feather versionShowcase (R)
R
Runtimes (3)