0
# Low-Level R Interface
1
2
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.
3
4
## Capabilities
5
6
### R Session Management
7
8
Initialize, configure, and manage the embedded R session.
9
10
```python { .api }
11
def initr(interactive=None, _want_setcallbacks: bool = True, _c_stack_limit=None):
12
"""
13
Initialize embedded R session.
14
15
Parameters:
16
- interactive: Set interactive mode (default: auto-detect)
17
- _want_setcallbacks: Enable R callbacks (default: True)
18
- _c_stack_limit: C stack size limit (default: R default)
19
20
Raises:
21
RuntimeError: If R initialization fails
22
"""
23
24
def process_revents():
25
"""
26
Process R events for graphics and UI.
27
28
Required for interactive R graphics and GUI components
29
to respond properly in embedded R sessions.
30
"""
31
```
32
33
### R Code Parsing and Evaluation
34
35
Low-level functions for parsing and evaluating R code with direct control over evaluation context.
36
37
```python { .api }
38
def parse(text: str, num: int = -1):
39
"""
40
Parse R code string into expression objects.
41
42
Parameters:
43
- text: R code as string
44
- num: Maximum number of expressions to parse (-1: all)
45
46
Returns:
47
ExprSexpVector containing parsed R expressions
48
49
Raises:
50
RRuntimeError: If parsing fails
51
"""
52
53
def evalr(source: str, maxlines: int = -1, envir=None, enclos=None):
54
"""
55
Evaluate R code string directly.
56
57
Parameters:
58
- source: R code to evaluate
59
- maxlines: Maximum lines to read (-1: all)
60
- envir: Evaluation environment (default: global environment)
61
- enclos: Enclosing environment for evaluation
62
63
Returns:
64
R object result of evaluation
65
66
Raises:
67
RRuntimeError: If evaluation fails
68
"""
69
70
def evalr_expr(expr, envir=None, enclos=None):
71
"""
72
Evaluate R expression object.
73
74
Parameters:
75
- expr: Parsed R expression (from parse())
76
- envir: Evaluation environment (default: global environment)
77
- enclos: Enclosing environment for evaluation
78
79
Returns:
80
R object result of evaluation
81
"""
82
83
def evalr_expr_with_visible(expr, envir=None):
84
"""
85
Evaluate R expression with visibility flag.
86
87
Parameters:
88
- expr: Parsed R expression
89
- envir: Evaluation environment (default: global environment)
90
91
Returns:
92
Tuple of (result, visible) where visible indicates if result should be printed
93
"""
94
```
95
96
### Vector Construction
97
98
Create R vectors directly from Python data with explicit type control.
99
100
```python { .api }
101
def vector(iterable, rtype: RTYPES):
102
"""
103
Create R vector from Python iterable with specified R type.
104
105
Parameters:
106
- iterable: Python sequence to convert
107
- rtype: R type from RTYPES enum (INTSXP, REALSXP, etc.)
108
109
Returns:
110
Appropriate SexpVector subclass for the specified type
111
112
Raises:
113
TypeError: If conversion is not possible
114
"""
115
116
def vector_memoryview(obj, sizeof_str: str, cast_str: str):
117
"""
118
Create memoryview for R vector data.
119
120
Parameters:
121
- obj: R vector object
122
- sizeof_str: Size specification string
123
- cast_str: Cast specification string
124
125
Returns:
126
Memoryview object for direct memory access
127
"""
128
```
129
130
### Core R Object Classes
131
132
Base classes representing R's fundamental object types (SEXP).
133
134
```python { .api }
135
class Sexp:
136
"""
137
Base class for all R objects (SEXP).
138
139
Provides low-level access to R object properties
140
including type, attributes, and memory management.
141
"""
142
@property
143
def typeof(self) -> RTYPES: ...
144
@property
145
def rclass(self): ...
146
147
class SexpVector(Sexp):
148
"""
149
Base class for R vectors with sequence interface.
150
151
Provides direct access to R vector data and
152
low-level vector operations.
153
"""
154
def __len__(self) -> int: ...
155
def __getitem__(self, key): ...
156
def __setitem__(self, key, value): ...
157
```
158
159
### Specialized Vector Classes
160
161
Low-level vector classes corresponding to R's internal vector types.
162
163
```python { .api }
164
class BoolSexpVector(SexpVector):
165
"""R logical vector (LGLSXP) with three-valued logic (TRUE/FALSE/NA)."""
166
167
class IntSexpVector(SexpVector):
168
"""R integer vector (INTSXP) with 32-bit signed integers."""
169
170
class FloatSexpVector(SexpVector):
171
"""R numeric vector (REALSXP) with double-precision floating point."""
172
173
class ComplexSexpVector(SexpVector):
174
"""R complex vector (CPLXSXP) with complex numbers."""
175
176
class ByteSexpVector(SexpVector):
177
"""R raw vector (RAWSXP) with byte data."""
178
179
class StrSexpVector(SexpVector):
180
"""R character vector (STRSXP) with string data."""
181
182
class ListSexpVector(SexpVector):
183
"""R list vector (VECSXP) containing other R objects."""
184
185
class PairlistSexpVector(SexpVector):
186
"""R pairlist (LISTSXP) for argument lists and environments."""
187
188
class ExprSexpVector(SexpVector):
189
"""R expression vector (EXPRSXP) containing parsed expressions."""
190
191
class LangSexpVector(SexpVector):
192
"""R language object (LANGSXP) representing unevaluated function calls."""
193
```
194
195
### Special R Object Types
196
197
Classes for R's special object types beyond vectors.
198
199
```python { .api }
200
class SexpEnvironment(Sexp):
201
"""
202
R environment object (ENVSXP) for variable scoping.
203
204
Provides dict-like interface to R environments
205
with proper scoping and inheritance behavior.
206
"""
207
def __getitem__(self, key: str): ...
208
def __setitem__(self, key: str, value): ...
209
def keys(self): ...
210
211
class SexpClosure(Sexp):
212
"""
213
R function object (CLOSXP) with formal arguments and body.
214
215
Represents user-defined R functions with parameter
216
lists, function bodies, and closure environments.
217
"""
218
219
class SexpSymbol(Sexp):
220
"""
221
R symbol object (SYMSXP) for unevaluated names.
222
223
Represents R variable names and symbols that
224
can be evaluated in specific environments.
225
"""
226
227
class SexpPromise(Sexp):
228
"""
229
R promise object (PROMSXP) for lazy evaluation.
230
231
Represents unevaluated R expressions that are
232
evaluated only when their value is needed.
233
"""
234
235
class SexpS4(Sexp):
236
"""
237
R S4 object (S4SXP) for formal object-oriented programming.
238
239
Represents R's formal S4 objects with slots
240
and method dispatch.
241
"""
242
243
class SexpExtPtr(Sexp):
244
"""
245
R external pointer (EXTPTRSXP) for C/C++ integration.
246
247
Wraps external pointers to C/C++ objects
248
for integration with compiled code.
249
"""
250
```
251
252
### Context Management
253
254
Manage R evaluation contexts and environments.
255
256
```python { .api }
257
def local_context(env=None, use_rlock: bool = True):
258
"""
259
Context manager for local R evaluation environment.
260
261
Parameters:
262
- env: R environment to use (default: new environment)
263
- use_rlock: Use R's thread lock (default: True)
264
265
Returns:
266
Context manager for scoped R evaluation
267
"""
268
269
def get_evaluation_context():
270
"""
271
Get current R evaluation environment (deprecated).
272
273
Returns:
274
Current evaluation context
275
276
Note: Deprecated in favor of evaluation_context context variable
277
"""
278
279
# Context variable for R evaluation environment
280
evaluation_context: Any
281
```
282
283
### Advanced Integration
284
285
Functions for deep R integration and Python-R interoperability.
286
287
```python { .api }
288
def rternalize(function=None, *, signature: bool = False):
289
"""
290
Make Python function callable from R.
291
292
Parameters:
293
- function: Python function to wrap (None for decorator use)
294
- signature: Include function signature information
295
296
Returns:
297
R-callable wrapper for Python function
298
299
Usage:
300
@rternalize
301
def my_python_func(x, y):
302
return x + y
303
"""
304
```
305
306
### Constants and Singletons
307
308
Low-level R constants and special values.
309
310
```python { .api }
311
# Singleton values
312
NULL: Any # R NULL value
313
MissingArg: Any # R missing argument placeholder
314
R_NilValue: Any # R nil value
315
316
# Missing values for each type
317
NA_Logical: Any # Logical NA
318
NA_Integer: Any # Integer NA
319
NA_Real: Any # Numeric NA
320
NA_Character: Any # Character NA
321
NA_Complex: Any # Complex NA
322
323
# Standard environments
324
globalenv: SexpEnvironment # R global environment
325
baseenv: SexpEnvironment # R base environment
326
emptyenv: SexpEnvironment # R empty environment
327
```
328
329
### R Type System
330
331
Enumeration of R's internal object types.
332
333
```python { .api }
334
class RTYPES:
335
"""Enumeration of R SEXP types."""
336
NILSXP: int # NULL
337
SYMSXP: int # Symbol
338
LISTSXP: int # Pairlist
339
CLOSXP: int # Function closure
340
ENVSXP: int # Environment
341
PROMSXP: int # Promise
342
LANGSXP: int # Language object
343
SPECIALSXP: int # Special function
344
BUILTINSXP: int # Builtin function
345
CHARSXP: int # Character string
346
LGLSXP: int # Logical vector
347
INTSXP: int # Integer vector
348
REALSXP: int # Numeric vector
349
CPLXSXP: int # Complex vector
350
STRSXP: int # Character vector
351
DOTSXP: int # Dot-dot-dot
352
ANYSXP: int # Any type
353
VECSXP: int # List vector
354
EXPRSXP: int # Expression vector
355
BCODESXP: int # Byte code
356
EXTPTRSXP: int # External pointer
357
WEAKREFSXP: int # Weak reference
358
RAWSXP: int # Raw vector
359
S4SXP: int # S4 object
360
```
361
362
### Exception Types
363
364
Exception classes for R runtime errors.
365
366
```python { .api }
367
class RRuntimeWarning(Warning):
368
"""Warning class for R runtime warnings."""
369
370
class RRuntimeError(RuntimeError):
371
"""Exception class for R runtime errors."""
372
```
373
374
### Usage Examples
375
376
```python
377
import rpy2.rinterface as rinterface
378
from rpy2.rinterface import RTYPES
379
380
# Initialize R session
381
rinterface.initr()
382
383
# Parse and evaluate R code
384
expr = rinterface.parse('x <- c(1, 2, 3, 4, 5)')
385
result = rinterface.evalr_expr(expr[0])
386
387
# Create vectors with explicit types
388
int_vector = rinterface.vector([1, 2, 3, 4, 5], RTYPES.INTSXP)
389
float_vector = rinterface.vector([1.1, 2.2, 3.3], RTYPES.REALSXP)
390
391
# Direct evaluation
392
mean_result = rinterface.evalr('mean(c(1, 2, 3, 4, 5))')
393
print(mean_result[0]) # 3.0
394
395
# Work with environments
396
global_env = rinterface.globalenv
397
global_env['my_var'] = int_vector
398
399
# Context management
400
with rinterface.local_context():
401
local_result = rinterface.evalr('x <- 42')
402
# x only exists in this context
403
404
# Make Python function available to R
405
@rinterface.rternalize
406
def python_add(x, y):
407
return x + y
408
409
# Now python_add can be called from R code
410
rinterface.evalr('result <- python_add(10, 20)')
411
```