user1717931
user1717931

Reputation: 2501

how to run auto.arima using rpy2

I want to call R's auto.arima function from Python. I think i have not yet fully understood this interface. Can someone help me here - to send a time series obj to R, call forecast related functions and get back the results?

This is what I have done so far:

from rpy2.robjects import r
from rpy2.robjects import pandas2ri

#create a python time series
count = range(1, 51)
df['count'] = count
df['date'] = pd.date_range('2016-01-01', '2016-02-19')
df.set_index('date', inlace = True)
df.sort_index(inplace = True)

pandas2ri.activate()
r_timeseries = pandas2ri.py2ri(df)
r('fit <- auto.arima(r_timeseries)')

I think I have to import some R packages (like forecast). Not sure how to go about doing that in Python, properly pass the python time series object to R etc.

In [63]: r_ts = pandas2ri.py2ri(df)

In [64]: r_ts
Out[64]:
<DataFrame - Python:0x1126a93f8 / R:0x7ff7bfa51bc8>
[IntVector]
  X0: <class 'rpy2.robjects.vectors.IntVector'>
  <IntVector - Python:0x1126a96c8 / R:0x7ff7be1af1c0>
[       1,        2,        3, ...,       48,       49,       50]

And, when I attempt to call forecast

In [83]: x = r('forecast(r_ts)')
/Library/Python/2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: Error in forecast(r_ts) : object 'r_ts' not found

  res = super(Function, self).__call__(*new_args, **new_kwargs)
---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-83-0765ffc30741> in <module>()
----> 1 x = r('forecast(r_ts)')

/Library/Python/2.7/site-packages/rpy2/robjects/__init__.pyc in __call__(self, string)
    319     def __call__(self, string):
    320         p = _rparse(text=StrSexpVector((string,)))
--> 321         res = self.eval(p)
    322         return conversion.ri2py(res)
    323

/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
    176                 v = kwargs.pop(k)
    177                 kwargs[r_k] = v
--> 178         return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
    179
    180 pattern_link = re.compile(r'\\link\{(.+?)\}')

/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
    104         for k, v in kwargs.items():
    105             new_kwargs[k] = conversion.py2ri(v)
--> 106         res = super(Function, self).__call__(*new_args, **new_kwargs)
    107         res = conversion.ri2ro(res)
    108         return res

RRuntimeError: Error in forecast(r_ts) : object 'r_ts' not found

I tried the following as well:

In [99]: f = r('forecast.auto.arima(r_ts)')
---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-99-1c4610d2740d> in <module>()
----> 1 f = r('forecast.auto.arima(r_ts)')

/Library/Python/2.7/site-packages/rpy2/robjects/__init__.pyc in __call__(self, string)
    319     def __call__(self, string):
    320         p = _rparse(text=StrSexpVector((string,)))
--> 321         res = self.eval(p)
    322         return conversion.ri2py(res)
    323

/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
    176                 v = kwargs.pop(k)
    177                 kwargs[r_k] = v
--> 178         return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
    179
    180 pattern_link = re.compile(r'\\link\{(.+?)\}')

/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
    104         for k, v in kwargs.items():
    105             new_kwargs[k] = conversion.py2ri(v)
--> 106         res = super(Function, self).__call__(*new_args, **new_kwargs)
    107         res = conversion.ri2ro(res)
    108         return res

RRuntimeError: Error in eval(expr, envir, enclos) :
  could not find function "forecast.auto.arima"

Upvotes: 0

Views: 2177

Answers (2)

Rosa Alejandra
Rosa Alejandra

Reputation: 732

you could try what I do

import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
pandas2ri.activate()

ro.r('library(forecast)')

rdf = pandas2ri.py2ri(df)
ro.globalenv['r_timeseries'] = rdf
pred = ro.r('as.data.frame(forecast(auto.arima(r_timeseries),h=5))')

this way, you can handle pred as a data frame like this

    Point Forecast  Lo 80  Hi 80  Lo 95  Hi 95
51              51     51     51     51     51
52              52     52     52     52     52
53              53     53     53     53     53
54              54     54     54     54     54
55              55     55     55     55     55

Upvotes: 5

lgautier
lgautier

Reputation: 11545

In the first attempt you are telling R to use a variable r_ts that it does not now much about (the name r_ts is defined in your Python namespace), and in the second attempt you are added to this a function name R does not know anything about. Both error message are precisely reporting this as a problem.

Your first attempt could be rewritten as:

x = r('forecast')(r_ts)

Upvotes: 0

Related Questions