Using uv in RStudio¶
For R projects that depend on Python packages, a uv virtual environment can be integrated directly into the RStudio app.
This integration is achieved using the renv
and reticulate
packages in R.
As a first step, install uv, if not already present, following the instructions in Setting up uv on UCloud. Then, create a uv virtual environment:
$ uv venv py_env
Install the required Python packages via command line, for example:
$ source py_env/bin/activate
$ uv pip install numpy
Next, create a new folder to set up the R project, which has to be integrated with the virtual environment created earlier:
$ mkdir /work/my_project
The R project is initialized directly in the RStudio console:
setwd('/work/my_project')
renv::init()
Sys.setenv(RENV_PATHS_CACHE = '/work/my_project/renv/cache')
Finally renv
must use an existing Python virtual environment.
This is achieved by installing the reticulate
package first and then passing the path of the virtual environment in the console:
install.packages("reticulate")
renv::use_python('/work/py_env/bin/python')
renv
will record and use the specified Python interpreter within the project.
This can also be used with pre-existing virtual environments and Conda environments.
The integration can be verified by running in the RStudio console:
library('reticulate')
np <- import('numpy')
np$arange(10)
Note
The Python interpreter can be found by writing the command which python
inside the uv environment.
Automated Setup¶
The integration process described above can be automated during job startup using the Initialization parameter. The following script performs the necessary setup:
#!/bin/bash
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create an R project folder
mkdir -p /work/my_project
# Initialize the R project with renv
Rscript -e "setwd('/work/my_project')"
Rscript -e "renv::init()"
# Write the renv settings to ~/.Rprofile
echo "Sys.setenv(RENV_PATHS_CACHE = '/work/my_project/renv/cache')" > ~/.Rprofile
echo "renv::load(project = '/work/my_project')" >> ~/.Rprofile
# Install reticulate
Rscript -e 'install.packages("reticulate")'
# Create a uv virtual environment
uv venv py_env
# Activate the environment and install desired packages
source py_env/bin/activate
uv pip install numpy
# Get the path to the Python interpreter and tell renv to use it
PYTHON_PATH=$(which python)
Rscript -e "renv::use_python('$PYTHON_PATH')"
Contents