在R中,可以使用以下命令绘制回归线:
res=lm(height~age)
abline(res)
根据http://msenux.redwoods.edu/math/R/regression.php
的建议我怎么能用rpy2做同样的事情?我试过了
from rpy2 import robjects
r = robjects.r
r.png('test.png')
x = range(10)
y = range(10)
r.plot(x, y)
r.abline(r.lm(x, y))
但被rpy2抱怨:
Error in formula.default(object, env = baseenv()) : invalid formula
Traceback (most recent call last):
File "plot_ratio_price.py", line 34, in <module>
r.abline(r.lm(x, y))
File "/Library/Python/2.7/site-packages/rpy2/robjects/functions.py", line 82, in __call__
return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
File "/Library/Python/2.7/site-packages/rpy2/robjects/functions.py", line 34, in __call__
res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in formula.default(object, env = baseenv()) : invalid formula
任何提示?谢谢!
答案 0 :(得分:2)
继续@joran的评论后,Rpy2要求你为公式提供一个特殊的对象。文档说明了班级robjects.Formula
represents an R formula。因此,在您的最后一行(对r.abline
的调用)之前,您需要创建一个公式对象并将其传递到lm()
来电。
顺便说一下,您的问题代码看起来足够接近您可能考虑将其用作模板的rpy2
示例:
import array
from rpy2.robjects import IntVector, Formula
from rpy2.robjects.packages import importr
stats = importr('stats')
x = IntVector(range(1, 10))
y = IntVector(range(1, 10))
fmla = Formula('y ~ x')
env = fmla.environment
env['x'] = x
env['y'] = y
fit = stats.lm(fmla)