如何将 None 转换为 R NULL
How to convert None to R NULL
阅读 Mapping rpy2 objects to arbitrary python objects 后,我认为以下将允许将 Python None 转换为 R NULL:
import rpy2.robjects.conversion as cv
import rpy2.robjects as robjs
from rpy2.robjects import default_converter
from rpy2.robjects.packages import importr
r_base = importr("base")
def _none2null(none_obj):
return robjs.r("NULL")
none_converter = cv.Converter("None converter")
none_converter.py2rpy.register(None, _none2null)
with cv.localconverter(default_converter + none_converter):
filesl = r_base.list_files(pattern=None)
但是,跟踪失败:
NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'NoneType'>'
如何处理?
Converter.register()
方法接受要转换的对象类型作为第一个参数,但您传递了一个实例。 None
是 NoneType
的实例:
NoneType = type(None)
NoneType() is None # True
并且您需要为 NoneType
定义转换,因此您可以只使用:
none_converter.py2rpy.register(type(None), _none2null)
阅读 Mapping rpy2 objects to arbitrary python objects 后,我认为以下将允许将 Python None 转换为 R NULL:
import rpy2.robjects.conversion as cv
import rpy2.robjects as robjs
from rpy2.robjects import default_converter
from rpy2.robjects.packages import importr
r_base = importr("base")
def _none2null(none_obj):
return robjs.r("NULL")
none_converter = cv.Converter("None converter")
none_converter.py2rpy.register(None, _none2null)
with cv.localconverter(default_converter + none_converter):
filesl = r_base.list_files(pattern=None)
但是,跟踪失败:
NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'NoneType'>'
如何处理?
Converter.register()
方法接受要转换的对象类型作为第一个参数,但您传递了一个实例。 None
是 NoneType
的实例:
NoneType = type(None)
NoneType() is None # True
并且您需要为 NoneType
定义转换,因此您可以只使用:
none_converter.py2rpy.register(type(None), _none2null)