【问题标题】:Error trying to use a R library with rpy2尝试将 R 库与 rpy2 一起使用时出错
【发布时间】:2023-07-04 05:08:01
【问题描述】:

我正在尝试使用 Rpy2 中的 forecast 包。我不知道如何在 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 时间序列还是尝试使用 R 中的 forecast 包时语法不正确。如果有人可以在这里帮助我,我将不胜感激。

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

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.

【问题讨论】:

    标签: python r time-series rpy2


    【解决方案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。

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

    【讨论】:

    • 没错。首先base = importr('base')然后 base.c 将指向正确的函数。如果不确定函数在哪里,可以使用wherefrom() (rpy.sourceforge.net/rpy2/doc-2.3/html/…)
    • 但是你真的需要在rpy2中使用base.c(1,2,3)吗?你不能只使用python列表吗?我认为提问者刚刚粘贴了一些 R 代码。
    • 在他的第一个代码 sn-p 中有f = fore(s, 5, level = c(80,95))。可以使用base.c()rpy2.robjects.vectors.IntVector()rpy2.robjects.vectors.FloatVector()。前者会猜测所有元素的通用类型。如果使用 python 列表,它当前被转换为 R 列表(与 R 原子向量不同)。
    最近更新 更多