Next: , Previous: Robj type, Up: Robj type  


3.2.1 Calling R objects

An object of type Robj is always callable. When it represents a R function, that function is invoked; if it is not a R function, an exception is raised (see R exceptions):

>>> callable(r.seq)
1
>>> callable(r.pi)
1
>>> r.pi()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
rpy.RException: Error: attempt to apply non-function

The arguments passed to the Robj object can be any Python object, including another Robj object. When an object of a standard Python type is passed, it is converted to a R type according to the rules described in Python to R. When a Robj object is passed, the R function receives the corresponding R object unchanged. Usually, you don’t need to think on these things, because the conversion works as one expects.

A Robj also supports keyword arguments, if the corresponding R function does it. The names of the keyword arguments are also under the name conversion rules described in R objects look up.

For example:

>>> r.seq(1, 3)
[1, 2, 3]
>>> r.seq(1, 3, by=0.5)
[1.0, 1.5, 2.0, 2.5, 3.0]
>>> r['options'](show_coef_Pvalues=0)
{'show.coef.Pvalues': 1}
>>> r.print_(r.seq)
function (...) 
UseMethod("seq")
<Robj object at 0x8acb010>

Return values of the call to a Robj object are also converted from R to Python. When no conversion is possible, an Robj object is returned, which holds a reference to the R object. This behavior is completely customizable (see R to Python).

Note that python uses a python dictionary to store named arguments. As a consequence the order named arguments will be lost in calls to R functions, and hence may not produce what an R programmer expects:

>>> set_default_mode(NO_CONVERSION)
>>> r.print_(r.c(0,a=1,b=2,c=3))
  a c b 
0 1 3 2
<Robj object at 0xbc89d0>
>>> set_default_mode(BASIC_CONVERSION)

To work around this problem, RObj provides the lcall method which expects a list containing 2 element (name, value) tuples instead of a list of named and unnamed arguments. Unnamed arguments are indicated by using None or ” as for the name element of the tuple. While this form is unwieldy, it is functional and is occasionally necessary:

>>> set_default_mode(NO_CONVERSION)
>>> r.print_(r.c.lcall( (('',0),('a',1),('b',2),('c',3)) ) )
  a b c 
0 1 2 3 
<Robj object at 0xbc89b8>
>>> set_default_mode(BASIC_CONVERSION)

[See see Conversion system for the meaning of set_default_mode. It is used here to prevent python from translating the output of c into a python dictionary (which loses element order) before print_ displays it.]


Next: , Previous: Robj type, Up: Robj type