Switching between a conversion and a no conversion mode, an operation often present when working with RPy-1.x, is no longer necessary with rpy2.
The approach of rpy2 is to have R-wrapping objects that implement interfaces of builtin Python types whenever possible, letting the Python layer access the objects the usual way and the wrapped R objects be used as they are by the R functions. For example, R vectors are mapped to Python objects implementing the __getitem__() method in the sequence protocol, so elements can be accessed easily.
There is a low-level mapping between R and Python objects performed behind the (Python-level) scene, done at the rpy2.rinterface level, while a higher-level mapping is done between low-level objects and higher-level objects. The later is performed by the functions:
Those functions can be redefined to suits one’s need. The easiest option is to write a custom function calling the default function when the custom conversion should not apply.
As an example, let’s assume that one want to return atomic values whenever an R numerical vector is of length one. This is only a matter of writing a new function ri2py that handles this, as shown below:
import rpy2.robjects as robjects
def my_ri2py(obj):
res = robjects.default_ri2py(obj)
if isinstance(res, robjects.Vector) and (len(res) == 1):
res = res[0]
return res
robjects.conversion.ri2py = my_ri2py
Then we can test it with:
>>> pi = robjects.r.pi
>>> type(pi)
<type 'float'>
The default behavior can be restored with:
>>> robjects.conversion.ri2py = default_ri2py
The docstrings for default_ri2py(), default_py2ri(), and py2ro() are:
Convert an rpy2.rinterface.Sexp object to a higher-level object, without copying the R object.
| Parameters: | o – object |
|---|---|
| Return type: | rpy2.robjects.RObject (and subclasses) |
Convert an arbitrary Python object to an rpy2.rinterface.Sexp object. Creates an R object with the content of the Python object, wich means data copying.
| Parameters: | o – object |
|---|---|
| Return type: | rpy2.rinterface.Sexp (and subclasses) |
Convert any Python object to an robject.
| Parameters: | o – object |
|---|---|
| Return type: | rpy2.robjects.RObject (and subclasses) |