python - 尝试将 R 库与 rpy2 一起使用时出错

标签 python r time-series rpy2

我正在尝试使用 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 时间序列还是在尝试使用 forecast 时语法不正确造成的。来自 R 的包裹。如果有人能在这里帮助我,我将不胜感激。

编辑:我自己解决了。
这是任何感兴趣的人的正确代码:
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.

最佳答案

您是否已阅读错误消息?

NameError: name 'c' is not defined

这个错误从何而来?
f = fore(s, 5, level = c(80,95))

哪个是python代码?

没有 c Python 中的函数 - 有一个 R 函数,但那时你不是在 R 中,而是在 Python 中。

尝试(这是未经测试的):
f = fore(s, 5, level = [80,95])

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

另外,我认为这行不通。如果您 read the documentation你会看到 importr获取对包的引用,并使用点号表示法调用包中的函数。您需要做的fore.thingYouWantToCall(whatever) .

关于python - 尝试将 R 库与 rpy2 一起使用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317141/

相关文章:

python - 使用 Panda 每月平均每分钟时间序列数据集

Python:如何使用 struct.pack_into 将不同类型的数据打包到字符串缓冲区中

python - 如何在 MacOs X 10.5 上安装 plpython?

r - R : error when trying to write an equivalent function n choose k

RStudio 显示不同的 $PATH 变量

python - 是否可以使用 FB Prophet 进行多元多步预测?

python - 如何在 Python 2.7 中使用 "setup.cfg"而不是 setup.py

python - Conda (Python) 虚拟环境不能从 Windows 移植到 Linux

r - 从逻辑模型中仅提取 p 值显着的系数

python - 添加特定日期之前的天数作为列