4

我正在尝试forecast使用 rpy2 使用 R 中的包。我不知道如何在 rpy2 中将列表转换为时间序列,所以我认为 pandas 时间序列也可以。

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))

运行f返回此错误:

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

我不知道错误是由于使用 pandas 时间序列还是在尝试使用forecastR 的包时语法不正确。如果有人可以在这里帮助我,我将不胜感激。

编辑:我自己解决了。这是任何有兴趣的人的正确代码:

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.
4

1 回答 1

1

你读过错误信息吗?

NameError: name 'c' is not defined

这个错误是从哪里来的?

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

哪个是python代码对?

Python 中没有c函数 - 有一个 R 函数,但此时你不在 R 中,你在 Python 中。

尝试(这是未经测试的):

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

使用 Python 的方括号来制作 Python 列表对象。这可能会作为向量传递给 R。

另外,我认为这行不通。如果您阅读文档,您会看到它importr会为您提供对包的引用,并使用点分表示法调用包中的函数。你需要做fore.thingYouWantToCall(whatever)

于 2012-11-10T08:38:39.517 回答