Rpy2 R Interface (rpy2-rinterface)
rpy2-rinterface provides a low-level CFFI-based interface between Python and the R programming language, allowing Python code to directly interact with the R interpreter, R objects, and R functions at a granular level. It forms the foundational layer for higher-level Rpy2 packages. The current version is 3.6.6, with frequent patch releases addressing bug fixes and minor improvements, and new minor versions released periodically.
Common errors
-
RuntimeError: R_HOME is not set.
cause The rpy2 library cannot find the R installation directory on your system.fixEnsure R is installed. Set the `R_HOME` environment variable to the root of your R installation (e.g., `os.environ['R_HOME'] = '/path/to/R'`) before importing `rpy2.rinterface`. -
OSError: cannot load library 'R' / DLL load failed while importing _rinterface_cffi_ext
cause The Python interpreter cannot find the R shared library (e.g., R.dll on Windows, libR.so on Linux, libR.dylib on macOS) or its dependencies.fixMake sure your R installation's `bin` directory (e.g., `R_HOME/bin/x64`) is included in your system's PATH environment variable. For Windows, ensure the correct architecture (32-bit vs 64-bit) matches your Python installation. -
AttributeError: module 'rpy2.rinterface' has no attribute 'R'
cause You are attempting to use the `R` class to access the R interpreter, which was removed in `rpy2` version 3.6.0.fixUpdate your code to use the new initialization pattern: `import rpy2.rinterface as rinterface; rinterface.initr()`. Access global R environments via `rinterface.baseenv` and `rinterface.globalenv`.
Warnings
- breaking The `rpy2.rinterface.R` class, which was previously used to access the R interpreter, was removed in version 3.6.0. Directly instantiating `R()` is no longer possible.
- gotcha rpy2-rinterface requires a pre-existing R installation on the system. If R is not installed or not discoverable in the system's PATH, Python will fail to load the R shared library.
- gotcha On Windows, loading the R shared library can be finicky. The `RPY2_CFFI_MODE` environment variable can switch between `API` and `EXT` modes, which might resolve issues.
Install
-
pip install rpy2-rinterface
Imports
- initr
from rpy2.rinterface import R
from rpy2.rinterface import initr
- baseenv
from rpy2.rinterface import baseenv
- evalr
from rpy2.rinterface import evalr
Quickstart
import os
import rpy2.rinterface as rinterface
# IMPORTANT: rpy2-rinterface requires a functional R installation on your system.
# If R is not in your system's PATH, you might need to set R_HOME:
# os.environ['R_HOME'] = '/path/to/R'
# os.environ['PATH'] += os.pathsep + os.path.join(os.environ['R_HOME'], 'bin')
try:
# Initialize the R interpreter
# This must be called before interacting with R.
rinterface.initr()
print("R interpreter initialized successfully.")
# Access R's base environment
base = rinterface.baseenv
# Evaluate R code directly as a string
r_code = 'x <- 1:10; mean(x)'
result = rinterface.parse(r_code).eval(base)
print(f"R evaluation (mean of 1:10): {result[0]} (R type: {result.rid})")
# Call an R function with Python data
r_sum_func = base['sum']
python_list = [10, 20, 30]
r_vector = rinterface.IntSexpVector(python_list)
sum_result = r_sum_func(r_vector)
print(f"Sum of {python_list} in R: {sum_result[0]}")
except rinterface.RRuntimeError as e:
print(f"R Runtime Error: {e}\nEnsure R is installed and R_HOME is correctly set if needed.")
except Exception as e:
print(f"An unexpected error occurred: {e}")