Next: , Previous: Class conversion, Up: R to Python


4.1.4 Basic conversion

This mode tries to convert a Robj object to a basic Python object. It can convert most of the R types to an adequate Python type; but, sometimes, some information is lost.

The following table shows the conversion of types. When converting lists of objects, the rules are applied recursively.

R object Python object Notes
—— —— ——
NULL None
Logical Boolean (1)(2)
Integer Plain integer (1)(2)
Real Float (1)(3)
Complex Complex (1)
String String (1)
Vector list or dictionary (1)(4)
List list or dictionary (1)(4)
Array Array or list (5)
Other (fails)

Notes:

(1)
In the R system there are no true scalar types. All values are vectors, with scalars represented by vectors of length one. In Python, however, there is a representational and conceptual difference between scalars immutable lists (tuples), and mutable lists. Thus, An R vector of length one could potentially be translated into any of three Python forms :
                  r("as.integer(1)")  -->  int(1)
                                      -->  [int(1),]
                                      -->  (int(1),)

It is impossible to tell which of these is best from the R object itself. With BASIC_CONVERSION, R assumes that a vector of length one should be translated as scalar, and that vectors with other lengths (including 0) should be translated into Python [] lists.

RPy 0.4.3 introduced the new VECTOR_CONVERSION mode (see Vector conversion), which always returns a python list regardless of the length of the R vector.

(2)
The R programming language has an integer value represented by ‘NA’ (not applicable) which is converted to and from Python as the minimum integer (which is the actual value in R). Be careful, because the semantic is completely different:
Python:
NA/100 –> (-sys.maxint-1)/100 != NA
R:
NA/100 –> NA

(3)
The IEEE float values NaN (not a number) and Inf (infinite) are also converted between Python and R.
(4)
Vectors and lists from R may have an attribute names, which are the names of the elements of the sequence. In those cases, the sequence is translated to a Python dictionary whose keys are the names, and the values are the corresponding values of the sequence. When there are no names, the vector or list is translated to a normal Python list.
(5)
When Numeric is installed, a R array is converted to a Numeric array. Otherwise, a list of nested lists is returned.

When converting R arrays, the column and row names are discarded. Also, for R data frames, row names are discarded while column names are kept. And many other R objects with complex attribute structure may loose some of its attributes when converted to Python objects. When it is necessary to keep all the information of an R object, it is better to use the CLASS_CONVERSION mode with proper classes (see Useful examples), or to use the NO_CONVERSION mode (see No conversion).