Rupert Rupert - 26 days ago 8
Python Question

how to use rpy2 to get n-dim array from python

I want to use python to some calculations and put the array data to r to get some plot.

For 1-dim array, I can use FloatVector to get right answer, but n-dim array error

(run following code)

(2-dim array)

import numpy as np
from rpy2.robjects.vectors import FloatVector
x = np.array([[1, 2], [3, 4]])
X = FloatVector(x)


error information:

`Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Program\Anaconda3\lib\site-packages\rpy2\robjects\vectors.py", line 456, in __init__
obj = FloatSexpVector(obj)
ValueError: Error while trying to convert element 0 to a double.`


Using numpy2ri could make error in some plot orders(like ggplot2)

I'd like to doing these all in spyder.

Answer

The conversion mechanism can be your friend:

from rpy2.robjects.conversion import localconverter
from rpy2.robjects import numpy2ri

with localconverter(numpy2ri.converter) as cv:
    X = cv.py2ro(x) # convert from *py*thon to *ro*bjects

Otherwise, this is happening because rpy2 is trying to iterate through the sequence x (the default behavior without interaction with numpy requested) and make each element through the iteration an R/rpy2 object. Here it does not work because x[i] is turned to a FloatVector and you cannot have a FloatVector of FloatVector elements (you could have a list of FloatVector though). Explictly, this is what is happening (and you'll trigger the same error):

FloatVector([FloatVector(y) for y in x])