使用rpy2将Python中的NULL转换为R

3

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)
2个回答

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

由于您代码依赖太多,我没有尝试过,但如果as_null如上所定义,您应该能够使用它。

crost(ts, w=as_null())

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

import rpy2.robjects as robj

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

谢谢,@jpcoleman,我找到了我喜欢的解决方案,要感谢你。我已经进行了编辑以添加它。 - rll

0
问题可能是由于NULL中的引号引起的。无法使用rpy2进行检查(因为存在安装问题)。下面是一个可以使用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']

无法使用rpy2测试问题。或许反引号是一种读取它的选择。
crost(ts, w = `NULL`)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接