R

What is R?

R is a statistical programming language, complete with broad OS support and a graphical library. It is frequently used with RStudio.

How is R loaded?

The below can be used to view all of the installations of R on a particular system, where this example uses Coeus.

$ module avail |& grep "^R"

R/3.3.3/gcc6.3

R/3.4.0/gcc6.3

R/3.4.0/intel

R/3.4.2/gcc7.2.0

R/3.5.0/gcc7.2.0

R/3.5.0/openmpi-2.0/gcc7.2.0

R/3.6.1/gcc7.2.0

R/3.6.1/openmpi-2.0/gcc7.2.0

How is R invoked?

To invoke the R interactive interpreter, use the below.

$ module load R/3.6.1/gcc7.2.0

$ R

> print("Hello, World!")

[1] "Hello, World!"

> quit()

Save workspace image? [y/n/c]: n

$

To invoke the R interpreter, use the below.

$ module load R/3.6.1/gcc7.2.0

$ cat hello_world.R

print("Hello, World!")


$ Rscript hello_world.R

[1] "Hello, World!"

How are R packages installed locally?

If you are using one R module

The easiest way to install packages locally is to create a directory in your home directory such as local/R_libs/ and a file .Renviron in your home directory that has the line:

 export R_LIBS=~/local/R_libs/

Then, in R, you can run:

> install.packages("package-name")

With the appropriate arguments and the package will be installed into ~/local/R_libs/.

You can also export this variable manually before running R.

If you are using several R modules

It is best to keep R packages separated based on which R version they are installed for/with. You can do so by having a specific directory for the libraries of each version of R you plan on using. Then, to install and read from these directories, the R_LIBS environment variable must be set depending on which version of R you are using. One way to do so is to export the appropriate R_LIBS variable when loading a different version of R. Another way is to set up an alias in your ~/.bashrc file that loads the module and exports the R_LIBS variable. 

For example if you planned on using R-3.4.0 and R-3.4.2. you could add the following lines to ~/.bashrc:

alias R-3.4.2='module load R/3.4.2/gcc7.2.0; export R_LIBS=~/local/R_libs/3.4.2/gcc7.2/'

alias R-3.4.0='module load R/3.4.0/gcc6.3; export R_LIBS=~/local/R_libs/3.4.0/gcc6.3/'

Create an R virtual environment

cd ~

git clone https://github.com/pyenv/pyenv.git .pyenv

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc

echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc

echo 'eval "$(pyenv init -)"' >> ~/.bashrc

source .bashrc

pyenv install mambaforge-23.11.0-0

pyenv global mambaforge-23.11.0-0

mamba create -n r_env r-essentials r-base

mamba init bash

source .bashrc

mamba activate r_env

# install a package if needed

mamba install r-raster

mamba list