5

I am using rpy2 to call R function from python.

from rpy2.robjects import *
result=r.someFunctioninR()   #someFunctioninR is a R function written by myself
if result==r('as.null()'):
     do something
else:
     do something else

The "result" returned by someFunctioninR() can be either NULL or other format. result==r('as.null()') does not work. Is there any other way I can get a True when result is NULL?

buhtz
  • 10,774
  • 18
  • 76
  • 149

1 Answers1

6

Try rpy2.rinterface.NULL or robj.r("NULL"):

In [1]: from rpy2 import robjects as robj

Create an R function that returns NULL:

In [2]: robj.r("nullfn = function(){NULL}")
Out[2]: <SignatureTranslatedFunction - Python:0x104ea5ef0 / R:0x1058be4a8>

In [3]: result = robj.r.nullfn()

In [4]: print result
NULL

In [5]: print result == robj.rinterface.NULL
True

In [6]: print result == None
False

edit: I just realized that your code above should work as is. I think your error is probably due to the return type of r.someFunctionInR() -- is it possible it's returning a vector of NULL values? Have you tried printing the value of result? If this doesn't work, you might share what someFunctionInR() is.

Noah
  • 21,451
  • 8
  • 63
  • 71