CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rpy2

Python interface to the R language (embedded R)

Pending
Overview
Eval results
Files

low-level-interface.mddocs/

Low-Level R Interface

Direct access to R's C API through CFFI for performance-critical applications, advanced R integration scenarios, and when fine-grained control over R objects is required.

Capabilities

R Session Management

Initialize, configure, and manage the embedded R session.

def initr(interactive=None, _want_setcallbacks: bool = True, _c_stack_limit=None):
    """
    Initialize embedded R session.
    
    Parameters:
    - interactive: Set interactive mode (default: auto-detect)
    - _want_setcallbacks: Enable R callbacks (default: True)
    - _c_stack_limit: C stack size limit (default: R default)
    
    Raises:
    RuntimeError: If R initialization fails
    """

def process_revents():
    """
    Process R events for graphics and UI.
    
    Required for interactive R graphics and GUI components
    to respond properly in embedded R sessions.
    """

R Code Parsing and Evaluation

Low-level functions for parsing and evaluating R code with direct control over evaluation context.

def parse(text: str, num: int = -1):
    """
    Parse R code string into expression objects.
    
    Parameters:
    - text: R code as string
    - num: Maximum number of expressions to parse (-1: all)
    
    Returns:
    ExprSexpVector containing parsed R expressions
    
    Raises:
    RRuntimeError: If parsing fails
    """

def evalr(source: str, maxlines: int = -1, envir=None, enclos=None):
    """
    Evaluate R code string directly.
    
    Parameters:
    - source: R code to evaluate
    - maxlines: Maximum lines to read (-1: all)
    - envir: Evaluation environment (default: global environment)
    - enclos: Enclosing environment for evaluation
    
    Returns:
    R object result of evaluation
    
    Raises:
    RRuntimeError: If evaluation fails
    """

def evalr_expr(expr, envir=None, enclos=None):
    """
    Evaluate R expression object.
    
    Parameters:
    - expr: Parsed R expression (from parse())
    - envir: Evaluation environment (default: global environment)  
    - enclos: Enclosing environment for evaluation
    
    Returns:
    R object result of evaluation
    """

def evalr_expr_with_visible(expr, envir=None):
    """
    Evaluate R expression with visibility flag.
    
    Parameters:
    - expr: Parsed R expression
    - envir: Evaluation environment (default: global environment)
    
    Returns:
    Tuple of (result, visible) where visible indicates if result should be printed
    """

Vector Construction

Create R vectors directly from Python data with explicit type control.

def vector(iterable, rtype: RTYPES):
    """
    Create R vector from Python iterable with specified R type.
    
    Parameters:
    - iterable: Python sequence to convert
    - rtype: R type from RTYPES enum (INTSXP, REALSXP, etc.)
    
    Returns:
    Appropriate SexpVector subclass for the specified type
    
    Raises:
    TypeError: If conversion is not possible
    """

def vector_memoryview(obj, sizeof_str: str, cast_str: str):
    """
    Create memoryview for R vector data.
    
    Parameters:
    - obj: R vector object
    - sizeof_str: Size specification string
    - cast_str: Cast specification string
    
    Returns:
    Memoryview object for direct memory access
    """

Core R Object Classes

Base classes representing R's fundamental object types (SEXP).

class Sexp:
    """
    Base class for all R objects (SEXP).
    
    Provides low-level access to R object properties
    including type, attributes, and memory management.
    """
    @property
    def typeof(self) -> RTYPES: ...
    @property
    def rclass(self): ...
    
class SexpVector(Sexp):
    """
    Base class for R vectors with sequence interface.
    
    Provides direct access to R vector data and
    low-level vector operations.
    """
    def __len__(self) -> int: ...
    def __getitem__(self, key): ...
    def __setitem__(self, key, value): ...

Specialized Vector Classes

Low-level vector classes corresponding to R's internal vector types.

class BoolSexpVector(SexpVector):
    """R logical vector (LGLSXP) with three-valued logic (TRUE/FALSE/NA)."""

class IntSexpVector(SexpVector):  
    """R integer vector (INTSXP) with 32-bit signed integers."""

class FloatSexpVector(SexpVector):
    """R numeric vector (REALSXP) with double-precision floating point."""

class ComplexSexpVector(SexpVector):
    """R complex vector (CPLXSXP) with complex numbers."""

class ByteSexpVector(SexpVector):
    """R raw vector (RAWSXP) with byte data."""

class StrSexpVector(SexpVector):
    """R character vector (STRSXP) with string data."""

class ListSexpVector(SexpVector):
    """R list vector (VECSXP) containing other R objects."""

class PairlistSexpVector(SexpVector):
    """R pairlist (LISTSXP) for argument lists and environments."""

class ExprSexpVector(SexpVector):
    """R expression vector (EXPRSXP) containing parsed expressions."""

class LangSexpVector(SexpVector):  
    """R language object (LANGSXP) representing unevaluated function calls."""

Special R Object Types

Classes for R's special object types beyond vectors.

class SexpEnvironment(Sexp):
    """
    R environment object (ENVSXP) for variable scoping.
    
    Provides dict-like interface to R environments
    with proper scoping and inheritance behavior.
    """
    def __getitem__(self, key: str): ...
    def __setitem__(self, key: str, value): ...
    def keys(self): ...

class SexpClosure(Sexp):
    """
    R function object (CLOSXP) with formal arguments and body.
    
    Represents user-defined R functions with parameter
    lists, function bodies, and closure environments.
    """

class SexpSymbol(Sexp):
    """
    R symbol object (SYMSXP) for unevaluated names.
    
    Represents R variable names and symbols that
    can be evaluated in specific environments.
    """

class SexpPromise(Sexp):
    """
    R promise object (PROMSXP) for lazy evaluation.
    
    Represents unevaluated R expressions that are
    evaluated only when their value is needed.
    """

class SexpS4(Sexp):
    """
    R S4 object (S4SXP) for formal object-oriented programming.
    
    Represents R's formal S4 objects with slots
    and method dispatch.
    """

class SexpExtPtr(Sexp):
    """
    R external pointer (EXTPTRSXP) for C/C++ integration.
    
    Wraps external pointers to C/C++ objects
    for integration with compiled code.
    """

Context Management

Manage R evaluation contexts and environments.

def local_context(env=None, use_rlock: bool = True):
    """
    Context manager for local R evaluation environment.
    
    Parameters:
    - env: R environment to use (default: new environment)
    - use_rlock: Use R's thread lock (default: True)
    
    Returns:
    Context manager for scoped R evaluation
    """

def get_evaluation_context():
    """
    Get current R evaluation environment (deprecated).
    
    Returns:
    Current evaluation context
    
    Note: Deprecated in favor of evaluation_context context variable
    """

# Context variable for R evaluation environment
evaluation_context: Any

Advanced Integration

Functions for deep R integration and Python-R interoperability.

def rternalize(function=None, *, signature: bool = False):
    """
    Make Python function callable from R.
    
    Parameters:
    - function: Python function to wrap (None for decorator use)
    - signature: Include function signature information
    
    Returns:
    R-callable wrapper for Python function
    
    Usage:
    @rternalize
    def my_python_func(x, y):
        return x + y
    """

Constants and Singletons

Low-level R constants and special values.

# Singleton values
NULL: Any              # R NULL value
MissingArg: Any        # R missing argument placeholder  
R_NilValue: Any        # R nil value

# Missing values for each type
NA_Logical: Any        # Logical NA
NA_Integer: Any        # Integer NA
NA_Real: Any          # Numeric NA  
NA_Character: Any      # Character NA
NA_Complex: Any       # Complex NA

# Standard environments
globalenv: SexpEnvironment    # R global environment
baseenv: SexpEnvironment      # R base environment  
emptyenv: SexpEnvironment     # R empty environment

R Type System

Enumeration of R's internal object types.

class RTYPES:
    """Enumeration of R SEXP types."""
    NILSXP: int      # NULL
    SYMSXP: int      # Symbol
    LISTSXP: int     # Pairlist  
    CLOSXP: int      # Function closure
    ENVSXP: int      # Environment
    PROMSXP: int     # Promise
    LANGSXP: int     # Language object
    SPECIALSXP: int  # Special function
    BUILTINSXP: int  # Builtin function
    CHARSXP: int     # Character string
    LGLSXP: int      # Logical vector
    INTSXP: int      # Integer vector
    REALSXP: int     # Numeric vector
    CPLXSXP: int     # Complex vector
    STRSXP: int      # Character vector
    DOTSXP: int      # Dot-dot-dot
    ANYSXP: int      # Any type
    VECSXP: int      # List vector
    EXPRSXP: int     # Expression vector
    BCODESXP: int    # Byte code
    EXTPTRSXP: int   # External pointer
    WEAKREFSXP: int  # Weak reference
    RAWSXP: int      # Raw vector
    S4SXP: int       # S4 object

Exception Types

Exception classes for R runtime errors.

class RRuntimeWarning(Warning):
    """Warning class for R runtime warnings."""

class RRuntimeError(RuntimeError):
    """Exception class for R runtime errors."""

Usage Examples

import rpy2.rinterface as rinterface
from rpy2.rinterface import RTYPES

# Initialize R session
rinterface.initr()

# Parse and evaluate R code
expr = rinterface.parse('x <- c(1, 2, 3, 4, 5)')
result = rinterface.evalr_expr(expr[0])

# Create vectors with explicit types
int_vector = rinterface.vector([1, 2, 3, 4, 5], RTYPES.INTSXP)
float_vector = rinterface.vector([1.1, 2.2, 3.3], RTYPES.REALSXP)

# Direct evaluation
mean_result = rinterface.evalr('mean(c(1, 2, 3, 4, 5))')
print(mean_result[0])  # 3.0

# Work with environments
global_env = rinterface.globalenv
global_env['my_var'] = int_vector

# Context management
with rinterface.local_context():
    local_result = rinterface.evalr('x <- 42')
    # x only exists in this context

# Make Python function available to R
@rinterface.rternalize
def python_add(x, y):
    return x + y

# Now python_add can be called from R code
rinterface.evalr('result <- python_add(10, 20)')

Install with Tessl CLI

npx tessl i tessl/pypi-rpy2

docs

environment-management.md

high-level-interface.md

index.md

jupyter-integration.md

low-level-interface.md

package-management.md

type-conversion.md

vectors-datatypes.md

tile.json