In R, one can use the following command for plotting regression line:
res=lm(height~age)
abline(res)
As suggested by http://msenux.redwoods.edu/math/R/regression.php
How can I do the same thing with rpy2? I tried
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))
but got complained by 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
Any hints? Thanks!
Following on to @joran’s comment, Rpy2 requires you provide a special object for the formula. The documentation says that the class
robjects.Formularepresents an R formula. So prior to your last line (the call tor.abline) you need to create a Formula object and pass that in to yourlm()call.By the way, your problem code looks close enough to the
rpy2example that you might consider using it as a template: