Python interface to the R language (embedded R)
—
Flexible conversion framework for automatic and manual type conversion between Python and R objects, with support for NumPy, pandas integration, and custom conversion rules.
The conversion system manages bidirectional type conversion between Python and R objects.
class Converter:
"""
Type conversion manager for Python-R object conversion.
Manages conversion rules and provides context for
automatic type conversion between Python and R.
"""
def py2rpy(self, obj):
"""
Convert Python object to R object.
Parameters:
- obj: Python object to convert
Returns:
R object equivalent
Raises:
NotImplementedError: If no conversion rule exists
"""
def rpy2py(self, obj):
"""
Convert R object to Python object.
Parameters:
- obj: R object to convert
Returns:
Python object equivalent
Raises:
NotImplementedError: If no conversion rule exists
"""
def __enter__(self):
"""Context manager entry."""
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
# Global conversion instances
default_converter: Converter # Default conversion rules
flatlist_converter: Converter # List-flattening converterManage conversion contexts for different conversion behaviors.
def get_conversion() -> Converter:
"""
Get current conversion context.
Returns:
Active converter instance
"""
def set_conversion(converter: Converter):
"""
Set conversion context.
Parameters:
- converter: Converter instance to activate
"""
# Context variable for current converter
converter_ctx: AnyStandalone functions for explicit type conversion.
def py2ro(obj):
"""
Convert Python object to R object using current converter.
Parameters:
- obj: Python object to convert
Returns:
R object equivalent
"""
def ro2py(obj):
"""
Convert R object to Python object using current converter.
Parameters:
- obj: R object to convert
Returns:
Python object equivalent
"""Automatic conversion between NumPy arrays and R vectors/matrices.
# Available in rpy2.robjects.numpy2ri module
def activate():
"""
Activate automatic NumPy conversions.
Enables bidirectional conversion between:
- NumPy arrays ↔ R vectors/matrices
- NumPy dtypes ↔ R vector types
- NumPy structured arrays ↔ R data frames
"""
def deactivate():
"""
Deactivate automatic NumPy conversions.
Returns to default conversion behavior
without NumPy-specific rules.
"""
# NumPy conversion context
numpy_converter: ConverterAutomatic conversion between pandas objects and R data structures.
# Available in rpy2.robjects.pandas2ri module
def activate():
"""
Activate automatic pandas conversions.
Enables bidirectional conversion between:
- pandas DataFrame ↔ R data.frame
- pandas Series ↔ R vectors
- pandas Index ↔ R character vectors
- pandas Categorical ↔ R factors
"""
def deactivate():
"""
Deactivate automatic pandas conversions.
Returns to default conversion behavior
without pandas-specific rules.
"""
# Pandas conversion context
pandas_converter: ConverterHelper classes and functions for conversion management.
class NameClassMap:
"""
Name to class mapping utility for conversion rules.
Maps object names or types to specific conversion
classes for customized conversion behavior.
"""
def __init__(self, mapping: dict): ...
def __getitem__(self, key): ...
def __setitem__(self, key, value): ...Built-in conversion rules between common Python and R types.
# Python → R conversions
# int → IntSexpVector
# float → FloatSexpVector
# bool → BoolSexpVector
# str → StrSexpVector
# list → ListSexpVector
# dict → ListSexpVector (named)
# None → NULL
# R → Python conversions
# IntSexpVector → list of int
# FloatSexpVector → list of float
# BoolSexpVector → list of bool
# StrSexpVector → list of str
# ListSexpVector → list or dict
# NULL → Noneimport rpy2.robjects as ro
from rpy2.robjects.conversion import Converter, get_conversion
import numpy as np
import pandas as pd
# Basic conversion using default converter
python_list = [1, 2, 3, 4, 5]
r_vector = ro.conversion.py2rpy(python_list)
print(type(r_vector)) # IntVector
# Convert back to Python
back_to_python = ro.conversion.rpy2py(r_vector)
print(back_to_python) # [1, 2, 3, 4, 5]
# Using conversion contexts
with ro.conversion.flatlist_converter:
# Lists are flattened during conversion
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_vector = ro.conversion.py2rpy(nested_list)
# NumPy integration
import rpy2.robjects.numpy2ri as numpy2ri
# Activate NumPy conversions
numpy2ri.activate()
# Convert NumPy array to R
numpy_array = np.array([1.1, 2.2, 3.3, 4.4, 5.5])
r_vector = ro.conversion.py2rpy(numpy_array)
print(type(r_vector)) # FloatVector
# NumPy matrix to R matrix
numpy_matrix = np.array([[1, 2, 3], [4, 5, 6]])
r_matrix = ro.conversion.py2rpy(numpy_matrix)
print(r_matrix.nrow, r_matrix.ncol) # 2 3
# Deactivate when done
numpy2ri.deactivate()
# Pandas integration
import rpy2.robjects.pandas2ri as pandas2ri
# Activate pandas conversions
pandas2ri.activate()
# Convert pandas DataFrame to R
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [1.1, 2.2, 3.3, 4.4, 5.5],
'C': ['a', 'b', 'c', 'd', 'e']
})
r_dataframe = ro.conversion.py2rpy(df)
print(type(r_dataframe)) # DataFrame
print(r_dataframe.colnames) # ['A', 'B', 'C']
# Convert pandas Series to R vector
series = pd.Series([10, 20, 30, 40, 50])
r_series = ro.conversion.py2rpy(series)
print(type(r_series)) # IntVector
# Pandas Categorical to R factor
categorical = pd.Categorical(['low', 'medium', 'high', 'low', 'high'])
r_factor = ro.conversion.py2rpy(categorical)
print(type(r_factor)) # FactorVector
pandas2ri.deactivate()
# Custom conversion context
class MyConverter(Converter):
"""Custom converter with special rules."""
def py2rpy(self, obj):
if isinstance(obj, str) and obj.startswith('DATE:'):
# Convert special date strings to R Date objects
date_str = obj[5:] # Remove 'DATE:' prefix
return ro.r(f'as.Date("{date_str}")')
return super().py2rpy(obj)
# Use custom converter
my_converter = MyConverter()
with my_converter:
special_date = "DATE:2023-12-25"
r_date = ro.conversion.py2rpy(special_date)
print(type(r_date)) # R Date object
# Check current conversion context
current_converter = get_conversion()
print(f"Current converter: {type(current_converter)}")
# Manual converter switching
from rpy2.robjects.conversion import set_conversion
set_conversion(ro.conversion.flatlist_converter)
# Now flatlist_converter is active
# Combined conversions for complex workflows
with numpy2ri.converter + pandas2ri.converter:
# Both NumPy and pandas conversions active
mixed_conversion = True# Create converter with specific rules
custom_converter = Converter("Custom converter")
# Add conversion rules (advanced usage)
@custom_converter.py2rpy.register
def py2rpy_custom_class(obj):
if isinstance(obj, MyCustomClass):
return convert_to_r_equivalent(obj)
return NotImplemented
# Chaining converters
combined = numpy2ri.converter + pandas2ri.converter + custom_converter
# Temporary conversion override
original_converter = get_conversion()
try:
set_conversion(combined)
# Perform conversions with combined rules
result = ro.conversion.py2rpy(complex_object)
finally:
set_conversion(original_converter)Install with Tessl CLI
npx tessl i tessl/pypi-rpy2