Skip to content
DHIS2.org Community GitHub

Make R-models compatible with Chap

This page covers how to set up the environment for R-based models using renv.

Environment options

renv environment (for R models)

Use renv_env to specify an renv.lock file for R models that use renv for dependency management:

renv_env: renv.lock

When CHAP runs your model, it will automatically:

  1. Look for the renv.lock file in your model directory
  2. Run renv::restore(prompt = FALSE) to install all required R packages
  3. Execute your R commands with the restored environment

Your model directory should contain:

  • renv.lock - The lockfile specifying exact package versions (generated by renv::snapshot())
  • renv/ directory - Contains renv activation scripts
  • .Rprofile - Auto-activates renv when R starts (typically contains source("renv/activate.R"))

Example MLproject file with renv:

name: my_r_model
renv_env: renv.lock
entry_points:
  train:
    parameters:
      train_data: str
      model: str
    command: "Rscript main.R train --train_data {train_data} --model {model}"
  predict:
    parameters:
      historic_data: str
      future_data: str
      model: str
      out_file: str
    command: "Rscript main.R predict --model {model} --historic_data {historic_data} --future_data {future_data} --out_file {out_file}"

Setting up renv for your R model

  1. Initialize renv in your R project:

    renv::init()
    
  2. Install your required packages:

    renv::install("dplyr")
    renv::install("argparser")
    # ... other packages
    
  3. Create the lockfile:

    renv::snapshot()
    

This creates renv.lock with exact versions of all dependencies, ensuring reproducible environments.

See the minimalist R model example for a complete working example.

Next steps