2

我正在尝试运行一个简单的线性回归(使用 Python 中的 rpy2)并在运行以下脚本时遇到了一个措辞奇怪的错误:

from numpy import array, rec
from numpy.random import normal as nprandom
from rpy2.robjects import numpy2ri, r

foo = array(range(10))
bar = foo + nprandom(0,1,10)

d = rec.fromarrays([foo, bar], names=('foo','bar'))
fit = r.lm('bar ~ foo', data=d)
print fit.rx2('coefficients')

这是控制台输出:

>>> from numpy import array, rec
>>> from numpy.random import normal as nprandom
>>> from rpy2.robjects import numpy2ri, r
>>> 
>>> foo = array(range(10))
>>> bar = foo + nprandom(0,1,10)
>>> 
>>> d = rec.fromarrays([foo, bar], names=('foo','bar'))
>>> fit = r.lm('bar ~ foo', data=d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/rpy2/robjects/functions.py", line 82, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "/usr/local/lib/python2.6/dist-packages/rpy2/robjects/functions.py", line 33, in __call__
    new_kwargs[k] = conversion.py2ri(v)
  File "/usr/local/lib/python2.6/dist-packages/rpy2/robjects/__init__.py", line 134, in default_py2ri
    raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o))))
ValueError: Nothing can be done for the type <class 'numpy.core.records.recarray'> at the moment.
>>> print fit.rx2('coefficients')

我正在运行 Python 2.6.5 并且有 numpy 版本 1.6.1

有谁知道是什么导致了这个错误?

4

1 回答 1

1

您需要添加:

rpy2.robjects.activate()

导入后numpy2ri这篇 SO 帖子引用了 rpy2 文档:

仅此导入就足以将 numpy 对象自动转换为 rpy2 对象。

为什么让它成为一个可选的导入,而它本来可以包含在函数 py2ri() 中(就像在为该函数提交的原始补丁中所做的那样)?

尽管两者都是有效且合理的选择,但设计决策是为了最大程度地将 rpy2 与 numpy 分离,并且不要假设自动安装 numpy 意味着程序员想要使用它。

希望这能解决您的问题。

于 2012-03-25T15:37:03.407 回答