使用数字作为RPy2中R函数的参数时出错

时间:2018-01-04 16:52:44

标签: python r python-3.x numpy rpy2

我试图在时间序列中使用R包tseriesChaos中的互信息函数,并找到第一个最小值,以确定延迟嵌入时间序列的最佳延迟。我写了以下函数来实现这个目的:

def determine_lag(tseries, plot):
numpser = numpy.asarray(tseries)
n = numpser.size
bins = 1 + math.log(n, 2)
z = 500 
emi = numpy.array(tseriesChaos.mutual(tseries, bins, z, plot))
x = emi[0]
it = numpy.nditer(emi)
while not it.finished:
    y = it[0]
    num = it.index
    if y > x:
        lag = num
        break
    else:
        x = y
    it.iternext()
else:
    showwarning(title='Error', message='No minimum found, delay set to 50')
    failed = True
    lag = 50
return lag, failed

其中tseriessoundfile.read在其他地方提取的时间序列,plotTRUEFALSE

但是,在尝试使用该函数时,R函数的参数转换中似乎会出现错误。输出如下:

Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "/Users/BrandonPlay/Soundbed 0.3/master.py", line 177, in Start
self.lag, failed = determine_lag(self.tseries, do_plot)
File "/Users/BrandonPlay/Soundbed 0.3/master.py", line 49, in determine_lag
emi = numpy.array(tseriesChaos.mutual(tseries, bins, z, plot))
File "/Users/BrandonPlay/Library/Python/3.6/lib/python/site-packages/rpy2/robjects/functions.py", line 178, in __call__
return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
File "/Users/BrandonPlay/Library/Python/3.6/lib/python/site-packages/rpy2/robjects/functions.py", line 102, in __call__
new_args = [conversion.py2ri(a) for a in args]
File "/Users/BrandonPlay/Library/Python/3.6/lib/python/site-packages/rpy2/robjects/functions.py", line 102, in <listcomp>
new_args = [conversion.py2ri(a) for a in args]
File "/Users/BrandonPlay/Library/Python/3.6/lib/python/site-packages/rpy2/robjects/numpy2ri.py", line 72, in numpy2ri
if not o.dtype.isnative:
AttributeError: 'float' object has no attribute 'dtype'

据我所知,当RPy2中将参数转换为R对象以传递给R函数的函数遇到参数z时,会发生此错误。当前设置(在函数调用之外分配z)试图修复错误;以前,我只是简单地将数字作为函数调用中的参数。

我甚至没有远程理解为什么参数转换器应该对一个简单的整数参数有困难,特别是因为bins也是一个整数并且处理正常。

有人知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

事实证明,问题出现了,因为我之前在程序中错误地激活了numpy2ri,将其分配给py2ri而不是使用numpy2ri.activate(),从而覆盖了正常py2ri 1}}例程,它将非numpy对象转换为r对象。我通过将所有内容都转换为numpy对象来尝试修复大量类似错误,我发现了这一点,包括使用numpy.array([numpy.int_(some_number)])来表示简单的整数参数。奇怪的是,numpy2ri.activate()从未发挥作用,而是发出类似class function has no method activate的错误,这非常奇怪,因为文档会告诉您这样做。最后,我完全删除了numpy2ri,并且事先使用tseriesnumpy tmseries = robjects.FloatVector(tseries.tolist())数组直接转换为R向量。