Search code examples
rpython-3.xnullrpy2

Convert NULL from Python to R using rpy2


In R often the NULL value is used as default. Using Python and RPy2, how can one explicitly provide a NULL argument?

None is not convertible (NotImplementedError), a string 'NULL' will just be converted to a string and result in an error during execution.

Take the following example using the tsintermittent package:

import numpy as np
from rpy2.robjects.packages import importr
from rpy2.robjects import numpy2ri

numpy2ri.activate()

tsintermittent = importr('tsintermittent')
crost = tsintermittent.crost

ts = np.random.randint(0,2,50) * np.random.randint(1,10,50)

# implicit ok, default w is NULL
# crost(ts)

# explicit - how to do it?
# RRunTimeError - non numeric argument
crost(ts, w='NULL')
# NotImplementedError
crost(ts, w=None)

Solution

  • You can use the r object to import as.null and then call that function. For example:

    from rpy2.robjects import r
    
    as_null = r['as.null']
    is_null = r['is.null']
    print(is_null(as_null())) #prints TRUE
    

    I didn't try your code because of all of its dependencies, but if as_null is defined as above, you should be able to use

    crost(ts, w=as_null())
    

    Alternatively, use the NULL object definition directly from robjects:

    import rpy2.robjects as robj
    
    print(is_null(robj.NULL)) #prints TRUE