<a id="software-r"></a>

# R

R can be used on Komondor in several ways. Before you start, make three choices:

1. **How you work:** in RStudio, with `R` in a terminal, or with `Rscript` in batch
   jobs.
2. **Which R environment you use:** the `cray-R` module, EESSI, or a container.
3. **Where extra R packages go:** a personal library in your home directory, or your own
   container.

#### TIP
**New to R on Komondor?** Start with RStudio on JupyterHub (see [RStudio on JupyterHub](#r-rstudio)).
When your analysis grows, move the heavy runs to batch jobs (see [Batch jobs with Rscript](#r-batch)).

#### WARNING
Run R computations **only on compute nodes**, in a Slurm job. On the login node, use
`cray-R` or EESSI only for very short checks, such as whether a package loads. Never
start a container on the login node, not even for a short task.

<a id="r-environments"></a>

## R environments

| Environment        | R version              | Included packages                                     | Best for                                                                     |
|--------------------|------------------------|-------------------------------------------------------|------------------------------------------------------------------------------|
| `cray-R` module    | 4.4.0 (default), 4.2.1 | base and recommended packages                         | quick, small tasks with few extra packages                                   |
| EESSI 2026.06      | 4.6.1                  | `R-bundle-CRAN`: several hundred common CRAN packages | common CRAN packages without installing anything                             |
| EESSI 2025.06      | 4.5.2                  | `R-bundle-Bioconductor` 3.22                          | Bioconductor (bioinformatics) packages                                       |
| RStudio container  | 4.5                    | tidyverse and other common data science packages      | interactive work in RStudio on JupyterHub                                    |
| Your own container | any                    | whatever you install into it                          | many or special packages, system libraries, portable and reproducible setups |

All examples below belong inside a Slurm job: an interactive job (see [R in a terminal](#r-terminal))
or a batch job (see [Batch jobs with Rscript](#r-batch)).

**cray-R**

```bash
module load cray-R          # R 4.4.0; cray-R/4.2.1.2 for the older version
```

**EESSI**

```bash
module load EESSI/2026.06
module load R-bundle-CRAN/2026.07-foss-2026.1    # also loads R/4.6.1
```

For Bioconductor packages, use EESSI 2025.06 instead:

```bash
module load EESSI/2025.06
module load R-bundle-Bioconductor/3.22-foss-2025b-R-4.5.2
```

To check whether a package is available, run `module spider <package>`. Loading
EESSI automatically purges previously loaded modules, including `cray-R`.
Choose one R environment for each session or job and load its application modules
after loading EESSI. Both `eessi` and `EESSI` names work. More details: [EESSI](eessi.md).

**Containers**

```bash
module load apptainer/1.4.4
apptainer exec -B /project/<project>,/scratch/<project> \
    /scratch/hub/shared/rstudio.sif Rscript analysis.R
```

The same command works with any other container that contains R: an existing one, such as
the [genomics container](genomics.md), or your own (see [A minimal R container](#r-container)).
`/project` and `/scratch` are not visible in a container unless you bind them with
`-B`. More details: [Container Environment](singularity.md).

<a id="r-packages"></a>

## Installing R packages

#### WARNING
A package library belongs to **one R environment and one R version**. Packages built in
different environments are not compatible, even when the R version is the same. Mixing
them leads to errors such as `undefined symbol` or `cannot open shared object file`.

`cray-R` and EESSI cannot install into their own, read-only library, so give each
environment its own personal library. Right after loading the environment, set
`R_LIBS_USER`. R replaces `%v` with the R version.

| Environment        | Line to add after loading it                              |
|--------------------|-----------------------------------------------------------|
| `cray-R`           | `export R_LIBS_USER=~/R/cray-R/%v`                        |
| EESSI 2026.06      | `export R_LIBS_USER=~/R/eessi-2026.06/%v`                 |
| EESSI 2025.06      | `export R_LIBS_USER=~/R/eessi-2025.06/%v`                 |
| RStudio container  | nothing: it uses `~/R/x86_64-conda-linux-gnu-library/4.5` |
| Your own container | nothing: install packages into the container image        |

R ignores a library directory that does not exist. Create it once for each environment:

```bash
Rscript -e 'dir.create(Sys.getenv("R_LIBS_USER"), recursive = TRUE)'
```

After that, `install.packages()` installs into this directory.

#### NOTE
Do not set `R_LIBS_USER` in `~/.Renviron`. Every R on Komondor reads that file,
including R in containers, and it overrides the value you set in your shell or job.

Your home quota is 20 GB and 100,000 files. If a large package collection does not fit,
use the same setup with a directory under `/project/<project>/<user>/` instead of `~`.
Check your quotas with `squota` (see [Storage Overview](../storage/overview.md)).

<a id="r-rstudio"></a>

## RStudio on JupyterHub

RStudio runs in your browser through [JupyterHub](jupyter.md), as a Slurm job on a
compute node.

**Start**

1. Log in to [JupyterHub](https://jupyter.hpc.kifu.hu/).
2. The first time, type a server name (for example `rstudio`) and click
   **Add new name**. Next time you can reuse the same server.
3. Click **start** in the row of your server.
4. Open the **Advanced** tab and set:
   * **Partition:** `cpu`
   * **CPUs:** as few as you need; 2 is enough for most interactive work.
   * **Memory:** leave empty for the default of 2000 MB per CPU, or set more.
   * **Job duration:** for example `04:00:00` for 4 hours.
   * Tick **Mount /project/$projectname** and **Mount /scratch/$projectname** if you
     need your project data. Your home directory is always available.
   * **Jupyter notebook environment:** `/scratch/hub/shared/rstudio.sif`
5. Click **Start**. If the nodes are in power-saving standby, starting can take
   10–15 minutes.
6. In the JupyterLab **Launcher**, click the **RStudio** icon.

The **Simple** tab also works and mounts your project and scratch storage automatically,
but it gives at least 8 CPUs and full hours only.

To return to a running server, click its link in the **URL** column of the server list.

**While you work**

* Use the **Files** pane and its `...` button to open `/project/<project>` or
  `/scratch/<project>`.
* `parallel::detectCores()` reports all cores of the node, not the ones you got. Use
  `as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1"))` instead.
* The session ends when the run time runs out, and unsaved work is lost.

**Stop**

1. Save your work and quit R with the power button at the top right of RStudio.
2. In JupyterLab, choose **File > Hub Control Panel**. The server list opens in a new
   window.
3. Click **stop** in the row of your server.

Closing the browser tab does **not** stop the job, and it keeps using your project’s
allocation. A stopped server can be started again or removed with **delete**.

For R in Jupyter notebooks instead of RStudio, choose
`/scratch/hub/shared/docker-stacks-r-notebook.sif` (R 4.5.3).

#### TIP
If JupyterLab opens an old terminal instead of the Launcher, close the terminal tab,
or open the address ending in `/lab?reset`.

<a id="r-terminal"></a>

## R in a terminal

For interactive work without RStudio, start an interactive Slurm job and run `R` in
it, with any of the environments above:

```bash
srun -p cpu -c 2 --mem-per-cpu=2000 -t 01:00:00 --pty bash -l
module load cray-R
export R_LIBS_USER=~/R/cray-R/%v
R
```

Type `q()` to quit R, then `exit` to end the job. A terminal opened in JupyterLab on
JupyterHub already runs on a compute node, so you can start `R` there directly.

<a id="r-batch"></a>

## Batch jobs with Rscript

An interactive session holds its CPUs and memory for the whole run time, also while you
read, think or are away, and all of that time is charged to your project. A batch job
uses the resources only while the script computes. Develop and test interactively on a
small sample, then run the full analysis as a batch job.

| Work interactively for               | Use `Rscript` in a batch job for              |
|--------------------------------------|-----------------------------------------------|
| writing and debugging code           | the full analysis once the code works         |
| exploring data and plots             | long runs (hours or days)                     |
| small tests on a data subset         | many runs with different inputs or parameters |
| editing R Markdown or Quarto reports | jobs that need many cores or much memory      |

Example `analysis.R`:

```r
library(parallel)
n_cores <- as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1"))

results <- mclapply(1:100, function(i) mean(rnorm(1e6)), mc.cores = n_cores)
saveRDS(results, "results.rds")
```

Example `analysis.sbatch`. Keep the `#SBATCH` lines and use **one** of the three
blocks below them:

```bash
#!/bin/bash
#SBATCH --job-name=r-job
#SBATCH --partition=cpu
#SBATCH --cpus-per-task=8
#SBATCH --mem-per-cpu=2000
#SBATCH --time=02:00:00
#SBATCH --output=r-job-%j.log

# cray-R
module load cray-R
export R_LIBS_USER=~/R/cray-R/%v
Rscript analysis.R

# EESSI
module load EESSI/2026.06
module load R-bundle-CRAN/2026.07-foss-2026.1
export R_LIBS_USER=~/R/eessi-2026.06/%v
Rscript analysis.R

# Container
module load apptainer/1.4.4
apptainer exec -B /project/<project>,/scratch/<project> \
    /scratch/hub/shared/rstudio.sif Rscript analysis.R
```

Submit the job and check its status:

```bash
sbatch analysis.sbatch
squeue --me
```

Output and error messages go to `r-job-<jobid>.log`. For more options, see
[Preparing Job Scripts (sbatch)](../tasks/sbatch.md).

<a id="r-container"></a>

## A minimal R container

Build your own container when you need many packages, system libraries, or a portable
setup. This recipe uses a [Rocker](https://rocker-project.org/) base image, which
installs CRAN packages as fast binary builds.

`r-analysis.def`:

```singularity
Bootstrap: docker
From: rocker/r-ver:4.6

%post
    install2.r --error --skipinstalled data.table ggplot2

%test
    Rscript -e 'library(data.table); library(ggplot2)'
```

Build it on a compute node, not on the login node:

```bash
module load apptainer/1.4.4
srun -p cpu -c 4 --mem-per-cpu=2000 -t 01:00:00 \
    apptainer build --fakeroot r-analysis.sif r-analysis.def
```

Run it in a batch job:

```bash
apptainer exec -B /project/<project> r-analysis.sif Rscript analysis.R
```

To add packages, edit the `install2.r` line and rebuild. Keep the `.def` file with the
image, so the setup can be rebuilt on another system. For build options and temporary
directories, see [Container Environment](singularity.md) and [Conda environments with Apptainer](conda-apptainer.md).

## Troubleshooting

| Problem                                                                                         | What to do                                                                                                                           |
|-------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|
| `install.packages()` says the library is not writable, or asks to create a<br/>personal library | Set `R_LIBS_USER` and create the directory (see [Installing R packages](#r-packages)).               |
| `undefined symbol` or `cannot open shared object file` when loading a package                   | The package was built in another R environment. Reinstall it in the library of<br/>the environment you use now.                      |
| `R_LIBS_USER` has no effect                                                                     | Remove the `R_LIBS_USER` line from `~/.Renviron`.                                                                                    |
| A package needs a system library that is missing                                                | Check whether EESSI has it (`module spider <package>`), or build your own<br/>container.                                             |
| `Disk quota exceeded`                                                                           | Check with `squota`. Move your library to project storage if your home is full.                                                      |
| The JupyterHub server stops right after starting                                                | Ask for more memory on the **Advanced** tab. To see the error, tick **Enable<br/>logging** and check `~/jupyterhub/logs`.            |
| The JupyterHub server takes long to start                                                       | The **Available Resources** table on the **Simple** tab shows free CPUs per<br/>partition. Ask for fewer CPUs or a shorter run time. |
| `/project` or `/scratch` is missing in RStudio                                                  | Stop the server and start it again with **Mount /project/$projectname** and<br/>**Mount /scratch/$projectname** ticked.              |

Questions: [hpc-support@dkf.hu](mailto:hpc-support@dkf.hu)
