Convert NULL from Python to R using rpy2

南楼画角 提交于 2021-02-10 12:05:45

问题


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)

回答1:


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



回答2:


The issue could be because of the quotes in NULL. Not able to check with rpy2 (because of having installation issues). Below, is a code that is working with pyper

from pyper import *
import numpy as np
r=R(use_pandas=True)
ts = np.random.randint(0,2,50) * np.random.randint(1,10,50)
r('library(tsintermittent)')
r.assign('ts1', ts)
r('out <- crost(ts1, w = NULL)')
out1 = r.get('out')
out1.keys()
#['frc.out', 'initial', 'weights', 'components', 'model', 'frc.in']

Can't test the issue with rpy2. May be backquotes would be an option to read it as it is

crost(ts, w = `NULL`)


来源:https://stackoverflow.com/questions/55636932/convert-null-from-python-to-r-using-rpy2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!