4

I'm trying to use the forecast package from R using rpy2. I couldn't find out how to convert a list into a timeseries in rpy2, so I figured a pandas time series would work as well.

from rpy2.robjects.packages import importr
from rpy2.robjects import r
fore = importr("forecast")
from pandas import *

data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
s = Series(data)

f = fore(s, 5, level = c(80,95))

Running f returns this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined

I don't know if the error is from using a pandas time series or incorrect syntax in trying to use the forecast package from R. If someone could help me out here I'd really appreciate it.

Edit: I solved it myself. Here's the correct code for anyone interested:

from rpy2.robjects.packages import importr
from rpy2.robjects import r
import rpy2.robjects.numpy2ri as rpyn
forecast = importr("forecast")

rcode = 'k = as.numeric(list(1, 2, 3, 4, 5, 6, 7, 8, 9))' #I just copied the contents of data in
r(rcode)
rcode1 = 'j <- ts(k)'
r(rcode1)
rcode2 = 'forecast(j, 5, level = c(80,95))'

x = r(rcode2)[1]
vector=rpyn.ri2numpy(x) #Converts from Float Vector to an array
lst = list(vector) #Converts the array to a list.

1 Answers1

1

Have you read the error message?

NameError: name 'c' is not defined

Where has that error come from?

f = fore(s, 5, level = c(80,95))

Which is python code right?

There's no c function in Python - there's an R function, but at that point you aren't in R, you're in Python.

Try (and this is untested):

f = fore(s, 5, level = [80,95])

using Python's square brackets to make a Python list object. This might get passed as a vector to R.

Also, I think this won't work. If you read the documentation you'll see that importr gets you a reference to the package, and to call a function in the package you use dotted notation. You need to do fore.thingYouWantToCall(whatever).

Spacedman
  • 92,590
  • 12
  • 140
  • 224
  • Exactly. First `base = importr('base')`, _then_ `base.c` will point to the right function. If unsure about where a function is, `wherefrom()` can be used (http://rpy.sourceforge.net/rpy2/doc-2.3/html/robjects_rpackages.html#rpy2.robjects.packages.wherefrom) – lgautier Nov 10 '12 at 16:25
  • But do you really need to use `base.c(1,2,3)` in rpy2? Can't you just use python lists? I think the questioner had just pasted in some R code. – Spacedman Nov 10 '12 at 16:37
  • In his first code snippet there is `f = fore(s, 5, level = c(80,95))`. Either `base.c()`, `rpy2.robjects.vectors.IntVector()`, or `rpy2.robjects.vectors.FloatVector()` can be used. The former will guess a common type for all the elements. If using a python list, it is currently translated to an R list (which is a different beast from an R atomic vector). – lgautier Nov 10 '12 at 17:26