使用 rpy2 将 NULL 从 Python 转换为 R

rll*_*rll 3 null r rpy2 python-3.x

在 R 中,该NULL值通常用作默认值。使用 Python 和 RPy2,如何显式提供参数NULL

None不可转换 ( NotImplementedError),字符串 'NULL' 将仅转换为字符串并在执行期间导致错误。

采取以下使用该tsintermittent包的示例:

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)
Run Code Online (Sandbox Code Playgroud)

Joh*_*man 5

您可以使用该r对象来导入as.null,然后调用该函数。例如:

from rpy2.robjects import r

as_null = r['as.null']
is_null = r['is.null']
print(is_null(as_null())) #prints TRUE
Run Code Online (Sandbox Code Playgroud)

我没有尝试你的代码,因为它的所有依赖项,但如果as_null定义如上,你应该能够使用

crost(ts, w=as_null())
Run Code Online (Sandbox Code Playgroud)

或者NULL,直接使用以下对象定义robjects

import rpy2.robjects as robj

print(is_null(robj.NULL)) #prints TRUE
Run Code Online (Sandbox Code Playgroud)