使用rpy2将R ListVector转换为Python列表 [英] Converting a R ListVector to a Python list with rpy2

查看:257
本文介绍了使用rpy2将R ListVector转换为Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数将项目放入Python列表中,并通过R中的函数将其放入,然后将它们作为R ListVector输出.问题是我在文档中找不到从ListVector转换为常规Python对象.这是我的代码:

I have a function that takes the items in a Python list, puts them through a function in R, and outputs them as a R ListVector. The problem is that I can't find in the documentation how to convert from a ListVector into a regular Python object. Here's my code:

from rpy2.robjects.packages import importr
from rpy2.robjects import r
forecast = importr("forecast")
parallel = importr("multicore")

data = [[1, 2, 3], [4, 5, 6,], [7, 8, 9]]

tuples = tuple(tuple(x) for x in data)

data_list = []
for i in range(0, len(data)):
    result1 = "k = as.numeric((list%r))" % (tuples[i],)
    data_list.append(result1)

def forecaster(item):
    rcode = item
    r(rcode)
    rcode1 = 'j <- ts(k)'
    r(rcode1)
    rcode2 = 'p <- parallel(forecast(k, 5, level = c(80,95)))'
    r(rcode2)
    rcode3 = 'collect(list(p))'
    return r(rcode3)


z = [forecaster(x) for x in data_list]

运行z给我这样的输出:

[<ListVector - Python:0x4e5f908 / R:0x4a0fcd8>
[ListVector]
<ListVector - Python:0x4e5f908 / R:0x4a0fcd8>
[ListVector], <ListVector - Python:0x4e5fcf8 / R:0x49f9c48>   

...等等.有人可以帮我弄清楚如何将这些ListVectors转换成我可以在Python中实际使用的东西吗?谢谢.

...And so on. Could someone please help me figure out how to convert these ListVectors into something I can actually use in Python? Thanks.

推荐答案

我使用rpy2做了一个类似的示例,如下所示:

I have done a similar example using rpy2 as follow:

    x = [1,2,3,4,1,2,3,4,1,2]
    v = robjects.FloatVector(x)
    t = robjects.r['ts'](v)
    fit = robjects.r['auto.arima'](t)
    next = robjects.r['forecast'](fit,h=1)

很明显,我正在做一个使用arima分析时间序列的简单示例.当我得到下一个时,我发现它是一个ListVector,然后使用以下代码获取所需的值.

It is clear to know that I was doing a simple example of using arima to analysis time seires.When I got the next, I found that it was a ListVector.Then I used codes as follow to get the value I wanted.

    count = len(next) - 2
    #ListVector->FloatVector->Float
    print next.rx('mean')[0][0]

谁知道这种方法对您是否有效,只需尝试一下

Who knows whether this method is effective to you or not, just try it

这篇关于使用rpy2将R ListVector转换为Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆