0
# Package Management
1
2
Import and manage R packages from Python with automatic function signature translation, Python-style calling conventions, and seamless integration with the R package ecosystem.
3
4
## Capabilities
5
6
### Package Import
7
8
Import R packages into Python namespace with automatic function wrapping and signature translation.
9
10
```python { .api }
11
def importr(name: str, lib_loc=None, robject_translations={},
12
signature_translation: bool = True, suppress_messages: bool = True,
13
on_conflict: str = 'fail', symbol_r2python=None,
14
symbol_resolve=None, data: bool = True) -> Package:
15
"""
16
Import R package and return Python wrapper.
17
18
Parameters:
19
- name: R package name to import
20
- lib_loc: Library location (default: R default library paths)
21
- robject_translations: Dictionary mapping R names to Python names
22
- signature_translation: Enable Python-style function signatures
23
- suppress_messages: Suppress R package loading messages
24
- on_conflict: Action on naming conflicts ('fail', 'warn', 'resolve')
25
- symbol_r2python: Function to convert R symbols to Python names
26
- symbol_resolve: Function to resolve naming conflicts
27
- data: Import package datasets
28
29
Returns:
30
Package wrapper with Python-accessible R functions
31
32
Raises:
33
PackageNotInstalledError: If R package is not installed or cannot be loaded
34
"""
35
```
36
37
### Package Installation Check
38
39
Check if R packages are installed and accessible.
40
41
```python { .api }
42
def isinstalled(name: str, lib_loc=None) -> bool:
43
"""
44
Check if R package is installed.
45
46
Parameters:
47
- name: R package name to check
48
- lib_loc: Library location to search (default: R default library paths)
49
50
Returns:
51
True if package is installed and loadable
52
"""
53
54
def quiet_require(name: str, lib_loc=None) -> bool:
55
"""
56
Load an R package quietly (suppressing messages).
57
58
Parameters:
59
- name: R package name to load
60
- lib_loc: Library location (default: R default library paths)
61
62
Returns:
63
True if package loaded successfully
64
"""
65
```
66
67
### R Package Management via R Commands
68
69
For package installation, removal, and management, use R commands directly through rpy2's R interface.
70
71
```python { .api }
72
# Package installation (via R)
73
# r('install.packages("package_name")')
74
# r('install.packages(c("pkg1", "pkg2"))')
75
76
# Package removal (via R)
77
# r('remove.packages("package_name")')
78
79
# Check installed packages (via R)
80
# r('installed.packages()')
81
82
# Update packages (via R)
83
# r('update.packages()')
84
```
85
86
### Package Wrapper Classes
87
88
Different types of package wrappers providing various levels of Python integration.
89
90
```python { .api }
91
class Package(ModuleType):
92
"""
93
Basic R package wrapper with direct function access.
94
95
Provides access to R package functions through Python
96
attribute access with minimal signature translation.
97
"""
98
def __getattr__(self, name: str): ...
99
100
@property
101
def __rdata__(self) -> 'PackageData': ...
102
103
class SignatureTranslatedPackage(Package):
104
"""
105
Package wrapper with Python-style function signatures.
106
107
Translates R parameter names to Python conventions and
108
provides more Pythonic calling patterns.
109
"""
110
111
class InstalledPackage(Package):
112
"""
113
Wrapper for installed R package with metadata access.
114
115
Provides information about installed packages including
116
version, dependencies, and description.
117
"""
118
@property
119
def version(self) -> str: ...
120
@property
121
def description(self) -> str: ...
122
123
class InstalledSTPackage(InstalledPackage):
124
"""
125
Installed package wrapper with signature translation.
126
127
Combines installed package metadata with signature
128
translation for enhanced Python integration.
129
"""
130
131
class WeakPackage(Package):
132
"""
133
Weak reference package wrapper for memory management.
134
135
Holds weak references to R package objects to prevent
136
memory leaks in long-running applications.
137
"""
138
```
139
140
### Package Discovery and Information
141
142
Classes and functions to discover and inspect packages.
143
144
```python { .api }
145
class InstalledPackages:
146
"""
147
Interface to query installed R packages.
148
149
Provides access to information about packages
150
installed in the R environment.
151
"""
152
def __init__(self): ...
153
def __iter__(self): ...
154
155
def data(package) -> 'PackageData':
156
"""
157
Get datasets from R package.
158
159
Parameters:
160
- package: Package object or name
161
162
Returns:
163
PackageData object with access to package datasets
164
"""
165
166
def wherefrom(symbol: str, startswith: str = None):
167
"""
168
Find which package provides a symbol.
169
170
Parameters:
171
- symbol: R symbol/function name to search for
172
- startswith: Filter packages starting with this string
173
174
Returns:
175
Information about packages containing the symbol
176
"""
177
178
class PackageData:
179
"""
180
Datasets in an R package.
181
182
R packages can distribute datasets as part of their
183
functionality. This class provides access to those datasets.
184
"""
185
def fetch(self, name: str): ...
186
```
187
188
### Code Execution Classes
189
190
Classes for handling R code parsing and execution.
191
192
```python { .api }
193
class ParsedCode(rinterface.ExprSexpVector):
194
"""
195
Parsed R code expression vector.
196
197
Represents R code that has been parsed into an expression
198
vector suitable for evaluation.
199
"""
200
201
class SourceCode(str):
202
"""
203
R source code with parsing capabilities.
204
205
String subclass that provides methods to parse R source
206
code into executable expressions.
207
"""
208
def parse(self): ...
209
```
210
211
### Exception Classes
212
213
Exceptions specific to package management operations.
214
215
```python { .api }
216
class LibraryError(ImportError):
217
"""Base exception for library/package related errors."""
218
219
class PackageNotInstalledError(LibraryError):
220
"""Exception raised when attempting to import non-installed R package."""
221
```
222
223
### Usage Examples
224
225
```python
226
from rpy2.robjects.packages import importr, isinstalled
227
from rpy2.robjects import r
228
229
# Check if package is installed
230
if isinstalled('ggplot2'):
231
print("ggplot2 is available")
232
else:
233
print("ggplot2 is not installed")
234
235
# Import common R packages
236
try:
237
stats = importr('stats')
238
base = importr('base')
239
utils = importr('utils')
240
print("Base R packages imported successfully")
241
except PackageNotInstalledError as e:
242
print(f"Package import failed: {e}")
243
244
# Use R functions through package interface
245
data = [1, 2, 3, 4, 5]
246
mean_result = stats.mean(data)
247
print(f"Mean: {mean_result[0]}")
248
249
# Install packages via R (requires proper R configuration)
250
try:
251
r('install.packages("ggplot2", repos="https://cran.r-project.org")')
252
print("Package installation initiated")
253
except Exception as e:
254
print(f"Installation failed: {e}")
255
256
# Import newly installed packages
257
try:
258
ggplot2 = importr('ggplot2')
259
print("ggplot2 imported successfully")
260
except PackageNotInstalledError:
261
print("ggplot2 installation may have failed or requires restart")
262
263
# Handle package import with custom translation
264
# Map R's snake_case functions to Python camelCase
265
translations = {
266
'read_csv': 'readCsv',
267
'write_csv': 'writeCsv'
268
}
269
270
if isinstalled('readr'):
271
readr = importr('readr', robject_translations=translations)
272
# Now can use readr.readCsv instead of readr.read_csv
273
274
# Access package metadata
275
try:
276
from rpy2.robjects.packages import InstalledPackages
277
installed = InstalledPackages()
278
279
# Iterate through installed packages
280
package_count = 0
281
for pkg in installed:
282
package_count += 1
283
if package_count <= 5: # Show first 5 packages
284
print(f"Installed package: {pkg}")
285
print(f"Total packages checked: {package_count}")
286
287
except Exception as e:
288
print(f"Could not list packages: {e}")
289
290
# Suppress package loading messages
291
quiet_stats = importr('stats', suppress_messages=True)
292
293
# Import with custom symbol resolution
294
def r_to_python_name(r_name):
295
"""Convert R names to Python-friendly names."""
296
return r_name.replace('.', '_').replace('-', '_')
297
298
if isinstalled('somepackage'):
299
custom_package = importr('somepackage', symbol_r2python=r_to_python_name)
300
301
# Handle naming conflicts
302
package_with_conflicts = importr('package_name', on_conflict='resolve')
303
304
# Access package without signature translation for better performance
305
if isinstalled('stats'):
306
fast_stats = importr('stats', signature_translation=False)
307
308
# Get package datasets
309
if isinstalled('datasets'):
310
datasets = importr('datasets', data=True)
311
iris_data = data(datasets).fetch('iris')
312
print(f"Iris dataset shape: {iris_data.nrow} x {iris_data.ncol}")
313
314
# Find which package provides a function
315
from rpy2.robjects.packages import wherefrom
316
function_info = wherefrom('lm') # Linear model function
317
print(f"lm function provided by: {function_info}")
318
```
319
320
### Working with Specific Package Types
321
322
```python
323
# Bioconductor packages
324
try:
325
# First install BiocManager if needed
326
r('''
327
if (!require("BiocManager", quietly = TRUE))
328
install.packages("BiocManager")
329
BiocManager::install(c("Biobase", "limma"))
330
''')
331
332
# Import Bioconductor packages
333
if isinstalled('Biobase'):
334
biobase = importr('Biobase')
335
print("Biobase imported successfully")
336
337
except Exception as e:
338
print(f"Bioconductor setup failed: {e}")
339
340
# Check and install multiple packages
341
required_packages = ['dplyr', 'ggplot2', 'tidyr']
342
missing_packages = []
343
344
for pkg in required_packages:
345
if not isinstalled(pkg):
346
missing_packages.append(pkg)
347
348
if missing_packages:
349
# Install missing packages
350
pkg_list = ', '.join([f'"{pkg}"' for pkg in missing_packages])
351
r(f'install.packages(c({pkg_list}))')
352
353
# Verify installation
354
for pkg in missing_packages:
355
if isinstalled(pkg):
356
print(f"{pkg} installed successfully")
357
else:
358
print(f"{pkg} installation failed")
359
360
# Import all required packages
361
imported_packages = {}
362
for pkg in required_packages:
363
if isinstalled(pkg):
364
imported_packages[pkg] = importr(pkg)
365
366
print(f"Successfully imported {len(imported_packages)} packages")
367
368
# Package version information
369
if isinstalled('stats'):
370
stats_pkg = InstalledPackage('stats')
371
print(f"Stats package version: {stats_pkg.version}")
372
print(f"Stats package description: {stats_pkg.description}")
373
```
374
375
### Package Management Best Practices
376
377
```python
378
# Always check if package is installed before importing
379
def safe_importr(package_name, **kwargs):
380
"""Safely import R package with error handling."""
381
if not isinstalled(package_name):
382
raise PackageNotInstalledError(f"Package '{package_name}' is not installed")
383
384
try:
385
return importr(package_name, **kwargs)
386
except Exception as e:
387
raise LibraryError(f"Failed to import '{package_name}': {e}")
388
389
# Use context managers for temporary package imports
390
from contextlib import contextmanager
391
392
@contextmanager
393
def temp_package(package_name, **import_args):
394
"""Temporarily import a package."""
395
if isinstalled(package_name):
396
pkg = importr(package_name, **import_args)
397
try:
398
yield pkg
399
finally:
400
# Package cleanup if needed
401
pass
402
else:
403
raise PackageNotInstalledError(f"Package '{package_name}' not available")
404
405
# Usage
406
with temp_package('ggplot2') as ggplot2:
407
# Use ggplot2 functions
408
plot = ggplot2.ggplot(data)
409
# Package reference goes out of scope after context
410
```