Alessandro Cosentino Alessandro Cosentino - 1 year ago 127
Python Question

Element-wise comparison of vector and scalar fails in rpy2 with Python 3

It looks like rpy2 doesn't behave exactly the same in Python3 and Python2. In particular, in Python 2.7.x, I am able to compare a Vector with a scalar, whereas in Python 3.5.x, if I try to do that, the following error is raised:

TypeError: unorderable types: IntVector() > int()

Here is a snippet of my code:

>>> from rpy2 import robjects
>>> x = robjects.IntVector([5, -1])
>>> x > 0

And here is an extract of my
pip freeze
(same in both environments):


I would like to understand if it's a bug in rpy2 or simply a different behaviour of some library that rpy2 relies on (numpy for example).

Answer Source

If a bug, I would think that it was with Python 2.

An R vector is a sequence and the default Python behavior does not make such comparisons possible. For example:

>>> [1,2,3] < 2
TypeError                                 Traceback (most recent call last)
<ipython-input-5-f7a2f4fe21e0> in <module>()
----> 1 [1,2,3] < 2

TypeError: unorderable types: list() < int()

On the other hand, R's vectorized counterpart can be called throught the delegator .ro (as in "R Operator"). See

>>> v = IntVector([1,2,3])
>>> < 2 
R object with classes: ('logical',) mapped to:
<BoolVector - Python:0x7fc7789a5a08 / R:0x22d25f8>
[       1,        0,        0]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download