Python is a popular all-purpose scripting language, while R is a scripting language mostly popular for data analysis, statistics, and graphics. If you are reading this, there are good chances that you are at least familiar with one or both. Having an interface between both languages to benefit from the libraries of one language while working in the other is desirable to many users. A number of tools have been developed to achieve this and a few popular options are detailed below.

Sections

 

Access to R from within Python

RPy2

  1. Load your desired R module:
    [rcs@scc1 ~] module load R/4.3.1
  2. Add the library path of the loaded R module to LD_LIBARY_PATH:
    [rcs@scc1 ~] export LD_LIBRARY_PATH=$R_HOME/lib:$LD_LIBRARY_PATH
  3. Create and activate your virtualenv or conda environment.
  4. Install RPy2 into your environment with pip:
    (my_newenv) [rcs@scc1 ~] pip install rpy2
  5. Import your R packages in Python:
    (my_newenv) [rcs@scc1 ~] python
    >from rpy2.robjects.packages import importr
    
    # import R's "base" package
    >base = importr('base')

    In essence, this is importing the R base package in the embedded R, and exposing all R objects in that package as Python objects. See the full RPy2 documentation for R Packages.

 

Access to Python from within R

Reticulate

  1. Load your desired Python (or Miniconda) module:
    [rcs@scc1 ~] module load python3/3.10.12
  2. Create and activate your virtualenv or conda environment.
  3. Load your desired R module:
    (my_newenv) [rcs@scc1 ~] module load R/4.3.1
  4. Install Reticulate into R:
    (my_newenv) [rcs@scc1 ~] R
    >install.packages('reticulate')
  5. Load Reticulate in R and check that the correct Python environment is being used:
    (my_newenv) [rcs@scc1 ~] R
    >library(reticulate)
    >py_config()
    python:         /projectnb/rcs/my_newenv/bin/python
    libpython:      /share/pkg.8/python3/3.10.12/install/lib/libpython3.10.so
    pythonhome:     /projectnb/rcs/my_newenv:/projectnb/rcs/my_newenv
    virtualenv:     /projectnb/rcs/my_newenv/bin/activate_this.py
    version:        3.10.12 (main, Jul 20 2023, 10:11:55) [GCC 8.5.0 20210514 (Red Hat 8.5.0-18)]
    numpy:          /projectnb/rcs/my_newenv/lib/python3.10/site-packages/numpy
    numpy_version:  1.26.2
    

    See the full Reticulate documentation for loading Python environments.

 

Back to top