or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

environment-management.mdhigh-level-interface.mdindex.mdjupyter-integration.mdlow-level-interface.mdpackage-management.mdtype-conversion.mdvectors-datatypes.md
tile.json

tessl/pypi-rpy2

Python interface to the R language (embedded R)

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/rpy2@3.6.x

To install, run

npx @tessl/cli install tessl/pypi-rpy2@3.6.0

index.mddocs/

rpy2

A 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.

Package Information

  • Package Name: rpy2
  • Language: Python
  • Installation: pip install rpy2
  • Version: 3.6.2
  • Dependencies: cffi >= 1.15.0, R installation
  • Optional: numpy, pandas, IPython for enhanced functionality

Core Imports

import rpy2.robjects as robjects
from rpy2.robjects import r, globalenv, NULL, Formula

Low-level interface:

import rpy2.rinterface as rinterface

Common 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_require

Basic Usage

import 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)')

Architecture

rpy2 uses a layered architecture that provides multiple levels of abstraction:

  • rpy2.rinterface: Low-level CFFI-based interface directly wrapping R's C API
  • rpy2.robjects: High-level object-oriented Python interface with automatic type conversion
  • rpy2.robjects.lib: Pythonic interfaces to popular R packages (ggplot2, dplyr, etc.)
  • rpy2.interactive: Simplified imports and REPL-focused tools
  • rpy2.ipython: IPython/Jupyter notebook integration with magic commands

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.

Capabilities

High-Level R Interface

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: R

High-Level Interface

R Vector and Data Types

Comprehensive 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 types

Vector and Data Types

R Formulas

Statistical 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 environment

R Package Management

Import 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): ...

Package Management

Low-Level R Interface

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): ...

Low-Level Interface

Type Conversion System

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: Converter

Type Conversion

R Environment Management

Work 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: Environment

Environment Management

Jupyter Integration

IPython 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

Jupyter Integration

Common Types

# 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