Python interface to the R language (embedded R)
npx @tessl/cli install tessl/pypi-rpy2@3.6.0A comprehensive Python-to-R bridge library that enables seamless integration between Python and R programming environments. rpy2 provides both low-level interface capabilities for direct access to R's C API and high-level object-oriented interfaces for intuitive R object manipulation from Python.
pip install rpy2import rpy2.robjects as robjects
from rpy2.robjects import r, globalenv, NULL, FormulaLow-level interface:
import rpy2.rinterface as rinterfaceCommon vector imports:
from rpy2.robjects.vectors import (IntVector, FloatVector, StrVector,
BoolVector, ByteVector, ComplexVector,
FactorVector, DataFrame, Matrix, Array)Package imports:
from rpy2.robjects.packages import importr, isinstalled, quiet_requireimport rpy2.robjects as robjects
from rpy2.robjects import r, globalenv
from rpy2.robjects.packages import importr
# Execute R code directly
r('x <- c(1, 2, 3, 4, 5)')
r('mean_x <- mean(x)')
result = r['mean_x'][0]
print(f"Mean: {result}")
# Import R packages
stats = importr('stats')
base = importr('base')
# Create R vectors from Python data
from rpy2.robjects.vectors import IntVector, FloatVector
python_list = [1, 2, 3, 4, 5]
r_vector = IntVector(python_list)
# Call R functions with Python data
r_mean = stats.mean(r_vector)
print(f"R mean result: {r_mean[0]}")
# Work with R data frames
from rpy2.robjects.vectors import DataFrame
import rpy2.robjects as ro
# Create a data frame
dataf = DataFrame({
'x': IntVector([1, 2, 3, 4, 5]),
'y': FloatVector([1.1, 2.2, 3.3, 4.4, 5.5]),
'labels': StrVector(['a', 'b', 'c', 'd', 'e'])
})
# Access R's global environment
globalenv['my_data'] = dataf
r('summary(my_data)')rpy2 uses a layered architecture that provides multiple levels of abstraction:
The design enables both direct R API access for performance-critical applications and convenient high-level interfaces for typical data science workflows, with seamless integration into the Python scientific computing ecosystem including NumPy, pandas, and Jupyter.
Primary interface for most users, providing Pythonic access to R objects, functions, and data structures with automatic type conversion between Python and R.
class R:
def __call__(self, string: str, invisible: bool = None, print_r_warnings: bool = None) -> Any: ...
def __getitem__(self, item: str) -> Any: ...
def __getattribute__(self, attr: str) -> Any: ...
def reval(string: str, envir = globalenv) -> Any: ...
# Global R session instance
r: RComprehensive Python wrappers for R's vector types including numeric, logical, character, and complex vectors, plus data frames, matrices, and arrays.
class IntVector(Vector): ...
class FloatVector(Vector): ...
class BoolVector(Vector): ...
class StrVector(Vector): ...
class ByteVector(Vector): ...
class ComplexVector(Vector): ...
class FactorVector(Vector): ...
class DataFrame: ...
class Matrix: ...
class Array: ...
# Specialized matrix/array types for each vector type
class IntMatrix(Matrix, IntVector): ...
class FloatMatrix(Matrix, FloatVector): ...
# ... and more specialized typesStatistical formula interface for R model specification with environment management capabilities.
class Formula:
def __init__(self, formula, environment=globalenv): ...
def getenvironment(self) -> Environment: ...
def setenvironment(self, val: Environment): ...
environment: Environment # Property for formula environmentImport and manage R packages from Python, with automatic function signature translation and Python-style calling conventions.
def importr(name: str, lib_loc=None, robject_translations={},
signature_translation: bool = True, suppress_messages: bool = True,
on_conflict: str = 'warn', data: bool = True) -> Package: ...
def install_packages(packages, lib=None, repos=None, type=None, **kwargs): ...
def remove_packages(packages, lib=None): ...Direct access to R's C API through CFFI for performance-critical applications and advanced R integration scenarios.
def initr(interactive=None, _want_setcallbacks: bool = True, _c_stack_limit=None): ...
def evalr(source: str, maxlines: int = -1, envir=None, enclos=None): ...
def parse(text: str, num: int = -1): ...
class Sexp: ...
class SexpVector(Sexp): ...
class SexpEnvironment(Sexp): ...Flexible conversion framework for automatic and manual type conversion between Python and R objects, with support for NumPy and pandas integration.
class Converter:
def py2rpy(self, obj): ...
def rpy2py(self, obj): ...
default_converter: ConverterWork with R environments, scoping, and evaluation contexts for advanced R programming patterns from Python.
class Environment:
def __getitem__(self, key: str): ...
def __setitem__(self, key: str, value): ...
def keys(self): ...
globalenv: Environment
baseenv: EnvironmentIPython magic commands and rich display integration for seamless R usage in Jupyter notebooks with automatic plot rendering.
def load_ipython_extension(ipython): ...
# Magic commands available after loading extension:
# %R single_line_r_code
# %%R
# multi_line_r_code# Missing values
NULL: Any
NA_Logical: Any
NA_Integer: Any
NA_Real: Any
NA_Character: Any
NA_Complex: Any
# Environments
globalenv: Environment
baseenv: Environment
emptyenv: Environment
# External pointers
class ExternalPointer: ...
# R Types Enum
class RTYPES:
NILSXP: int
INTSXP: int
REALSXP: int
LGLSXP: int
STRSXP: int
VECSXP: int
LISTSXP: int
CLOSXP: int
ENVSXP: int
# ... additional R types