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
r(rcode1)
rcode2 = 'p
r(rcode2)
rcode3 = 'collect(list(p))'
return r(rcode3)
z = [forecaster(x) for x in data_list]
Running z gives me output like this:
[
[ListVector]
[ListVector],
...And so on. Could someone please help me figure out how to convert these ListVectors into something I can actually use in Python? Thanks.
解决方案
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)
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