Rpy2 R Interface (rpy2-rinterface)

3.6.6 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the R interpreter, evaluate R code, and call R functions using `rpy2.rinterface`. It highlights the crucial step of calling `initr()` and interacting with R's base environment. Users must have R installed on their system and ensure it's discoverable (e.g., via `R_HOME` environment variable or system PATH).

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}")

view raw JSON →