首页 > 解决方案 > 使用 rpy2 将 NULL 从 Python 转换为 R

问题描述

在 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)

标签: rpython-3.xnullrpy2

解决方案


您可以使用该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

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

crost(ts, w=as_null())

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

import rpy2.robjects as robj

print(is_null(robj.NULL)) #prints TRUE

推荐阅读