Python interface to the R language (embedded R)
npx @tessl/cli install tessl/pypi-rpy2@3.6.00
# rpy2
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: rpy2
7
- **Language**: Python
8
- **Installation**: `pip install rpy2`
9
- **Version**: 3.6.2
10
- **Dependencies**: cffi >= 1.15.0, R installation
11
- **Optional**: numpy, pandas, IPython for enhanced functionality
12
13
## Core Imports
14
15
```python
16
import rpy2.robjects as robjects
17
from rpy2.robjects import r, globalenv, NULL, Formula
18
```
19
20
Low-level interface:
21
22
```python
23
import rpy2.rinterface as rinterface
24
```
25
26
Common vector imports:
27
28
```python
29
from rpy2.robjects.vectors import (IntVector, FloatVector, StrVector,
30
BoolVector, ByteVector, ComplexVector,
31
FactorVector, DataFrame, Matrix, Array)
32
```
33
34
Package imports:
35
36
```python
37
from rpy2.robjects.packages import importr, isinstalled, quiet_require
38
```
39
40
## Basic Usage
41
42
```python
43
import rpy2.robjects as robjects
44
from rpy2.robjects import r, globalenv
45
from rpy2.robjects.packages import importr
46
47
# Execute R code directly
48
r('x <- c(1, 2, 3, 4, 5)')
49
r('mean_x <- mean(x)')
50
result = r['mean_x'][0]
51
print(f"Mean: {result}")
52
53
# Import R packages
54
stats = importr('stats')
55
base = importr('base')
56
57
# Create R vectors from Python data
58
from rpy2.robjects.vectors import IntVector, FloatVector
59
python_list = [1, 2, 3, 4, 5]
60
r_vector = IntVector(python_list)
61
62
# Call R functions with Python data
63
r_mean = stats.mean(r_vector)
64
print(f"R mean result: {r_mean[0]}")
65
66
# Work with R data frames
67
from rpy2.robjects.vectors import DataFrame
68
import rpy2.robjects as ro
69
70
# Create a data frame
71
dataf = DataFrame({
72
'x': IntVector([1, 2, 3, 4, 5]),
73
'y': FloatVector([1.1, 2.2, 3.3, 4.4, 5.5]),
74
'labels': StrVector(['a', 'b', 'c', 'd', 'e'])
75
})
76
77
# Access R's global environment
78
globalenv['my_data'] = dataf
79
r('summary(my_data)')
80
```
81
82
## Architecture
83
84
rpy2 uses a layered architecture that provides multiple levels of abstraction:
85
86
- **rpy2.rinterface**: Low-level CFFI-based interface directly wrapping R's C API
87
- **rpy2.robjects**: High-level object-oriented Python interface with automatic type conversion
88
- **rpy2.robjects.lib**: Pythonic interfaces to popular R packages (ggplot2, dplyr, etc.)
89
- **rpy2.interactive**: Simplified imports and REPL-focused tools
90
- **rpy2.ipython**: IPython/Jupyter notebook integration with magic commands
91
92
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.
93
94
## Capabilities
95
96
### High-Level R Interface
97
98
Primary interface for most users, providing Pythonic access to R objects, functions, and data structures with automatic type conversion between Python and R.
99
100
```python { .api }
101
class R:
102
def __call__(self, string: str, invisible: bool = None, print_r_warnings: bool = None) -> Any: ...
103
def __getitem__(self, item: str) -> Any: ...
104
def __getattribute__(self, attr: str) -> Any: ...
105
106
def reval(string: str, envir = globalenv) -> Any: ...
107
108
# Global R session instance
109
r: R
110
```
111
112
[High-Level Interface](./high-level-interface.md)
113
114
### R Vector and Data Types
115
116
Comprehensive Python wrappers for R's vector types including numeric, logical, character, and complex vectors, plus data frames, matrices, and arrays.
117
118
```python { .api }
119
class IntVector(Vector): ...
120
class FloatVector(Vector): ...
121
class BoolVector(Vector): ...
122
class StrVector(Vector): ...
123
class ByteVector(Vector): ...
124
class ComplexVector(Vector): ...
125
class FactorVector(Vector): ...
126
class DataFrame: ...
127
class Matrix: ...
128
class Array: ...
129
# Specialized matrix/array types for each vector type
130
class IntMatrix(Matrix, IntVector): ...
131
class FloatMatrix(Matrix, FloatVector): ...
132
# ... and more specialized types
133
```
134
135
[Vector and Data Types](./vectors-datatypes.md)
136
137
### R Formulas
138
139
Statistical formula interface for R model specification with environment management capabilities.
140
141
```python { .api }
142
class Formula:
143
def __init__(self, formula, environment=globalenv): ...
144
def getenvironment(self) -> Environment: ...
145
def setenvironment(self, val: Environment): ...
146
environment: Environment # Property for formula environment
147
```
148
149
### R Package Management
150
151
Import and manage R packages from Python, with automatic function signature translation and Python-style calling conventions.
152
153
```python { .api }
154
def importr(name: str, lib_loc=None, robject_translations={},
155
signature_translation: bool = True, suppress_messages: bool = True,
156
on_conflict: str = 'warn', data: bool = True) -> Package: ...
157
158
def install_packages(packages, lib=None, repos=None, type=None, **kwargs): ...
159
def remove_packages(packages, lib=None): ...
160
```
161
162
[Package Management](./package-management.md)
163
164
### Low-Level R Interface
165
166
Direct access to R's C API through CFFI for performance-critical applications and advanced R integration scenarios.
167
168
```python { .api }
169
def initr(interactive=None, _want_setcallbacks: bool = True, _c_stack_limit=None): ...
170
def evalr(source: str, maxlines: int = -1, envir=None, enclos=None): ...
171
def parse(text: str, num: int = -1): ...
172
173
class Sexp: ...
174
class SexpVector(Sexp): ...
175
class SexpEnvironment(Sexp): ...
176
```
177
178
[Low-Level Interface](./low-level-interface.md)
179
180
### Type Conversion System
181
182
Flexible conversion framework for automatic and manual type conversion between Python and R objects, with support for NumPy and pandas integration.
183
184
```python { .api }
185
class Converter:
186
def py2rpy(self, obj): ...
187
def rpy2py(self, obj): ...
188
189
default_converter: Converter
190
```
191
192
[Type Conversion](./type-conversion.md)
193
194
### R Environment Management
195
196
Work with R environments, scoping, and evaluation contexts for advanced R programming patterns from Python.
197
198
```python { .api }
199
class Environment:
200
def __getitem__(self, key: str): ...
201
def __setitem__(self, key: str, value): ...
202
def keys(self): ...
203
204
globalenv: Environment
205
baseenv: Environment
206
```
207
208
[Environment Management](./environment-management.md)
209
210
### Jupyter Integration
211
212
IPython magic commands and rich display integration for seamless R usage in Jupyter notebooks with automatic plot rendering.
213
214
```python { .api }
215
def load_ipython_extension(ipython): ...
216
217
# Magic commands available after loading extension:
218
# %R single_line_r_code
219
# %%R
220
# multi_line_r_code
221
```
222
223
[Jupyter Integration](./jupyter-integration.md)
224
225
## Common Types
226
227
```python { .api }
228
# Missing values
229
NULL: Any
230
NA_Logical: Any
231
NA_Integer: Any
232
NA_Real: Any
233
NA_Character: Any
234
NA_Complex: Any
235
236
# Environments
237
globalenv: Environment
238
baseenv: Environment
239
emptyenv: Environment
240
241
# External pointers
242
class ExternalPointer: ...
243
244
# R Types Enum
245
class RTYPES:
246
NILSXP: int
247
INTSXP: int
248
REALSXP: int
249
LGLSXP: int
250
STRSXP: int
251
VECSXP: int
252
LISTSXP: int
253
CLOSXP: int
254
ENVSXP: int
255
# ... additional R types
256
```