2012-03-25 12 views
2

我想運行一個簡單的線性迴歸(使用rpy2從Python),並遇到一個奇怪的措辭運行下面的腳本時出錯:'ValueError:沒有什麼可以做的類型<class'numpy.core.records.recarray'>此刻'錯誤

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

是否有任何人知道是什麼正在造成錯誤?

回答

1

您需要添加:

rpy2.robjects.activate() 

進口numpy2ri後。 This SO post參考rpy2文檔:

That import alone is sufficient to switch an automatic conversion of numpy objects into rpy2 objects.

Why make this an optional import, while it could have been included in the function py2ri() (as done in the original patch submitted for that function) ?

Although both are valid and reasonable options, the design decision was taken in order to decouple rpy2 from numpy the most, and do not assume that having numpy installed automatically meant that a programmer wanted to use it.

希望這可以解決您的問題。

相關問題