Install R Packages

This page describes how to install an R package in a CoCalc project.

CoCalc already includes hundreds of R packages, but you can install even more or update them inside your project.

Warning

Your project must have the “Internet access” upgrade in order to download software from a remote repository (i.e. CRAN) to your project. The install command will not work unless you upgrade your project to have internet access.

Otherwise you have to download the tarball of the R package to your own machine, and upload it to your project. Then, you can tell R to install the package directly from there as a local file.

In a nutshell, a CoCalc project is a Linux environment inside a Docker container. This means, almost everything you can do as a “normal” Linux user also works. In particular, you can install packages locally, such that R instances can pick them up.

Install requests

If a package may have general use but is not already installed in CoCalc, please open a support request to tell us to install it globally for everyone. Please include information about special dependencies or a specific example to test it.

Install a package

Jupyter Notebook

It is also possible to install packages directly via a Jupyter Notebook. The drawback compared with the Terminal option above is the lack of interactivity.

To be able to install into your local package library in your home directory, you have to make sure such a directory exists and tell the install.packages command – it is defined by Sys.getenv("R_LIBS_USER").

Otherwise you end up with errors like:

Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning message in install.packages("<package name>"):
“'lib = "/usr/local/lib/R/site-library"' is not writable”

To install packages into your own collection of packages, run this in a notebook cell:

dir.create(path = Sys.getenv("R_LIBS_USER"), showWarnings = FALSE, recursive = TRUE)
install.packages("<name of package>", lib = Sys.getenv("R_LIBS_USER"), repos = "https://cran.rstudio.com/")

Credits: stack overflow post

Note: If your Sys.getenv("R_LIBS_USER") already exists, a freshly started kernel will already know about it. You can check this by running .libPaths(). If the first listed path starts with /home/user/R/... you can run install.packages without any errors.

Aftermath

The above will install R packages for use with CoCalc worksheets (%r mode) and Jupyter notebooks using default R. The Sage binary may be built with a different release of R. Use R-sage instead of R to install packages for it.