How to convert complex matrix R to numpy array using rpy2

it is clear to me how to convert a float / double R-matrix to a numpy array, but I get an error if the matrix is complex .

Example:

import numpy as np
import rpy2.robjects as robjects
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()

m1=robjects.IntVector(range(10))
m2 = robjects.r.matrix(robjects.r['as.complex'](m1), nrow=5)
tmp=np.array(m2, dtype=complex) #ValueError: invalid __array_struct__

      

The problem persists with the following line of code:

tmp=np.array(m2)

      

Everything works fine if the matrix is not complicated :

m2 = robjects.r.matrix(m1, nrow=5)
tmp=np.array(m2)

      

Thanks for any help!

PS: Note that the following dirty trick solves the problem, but doesn't really answer the question:

tmp=np.array(robjects.r.Re(m2))+1j*np.array(robjects.r.Im(m2))

      

PS2: nobody seems to be able to answer this question, should we conclude that there is a bug in rpy2?

+3


source to share


1 answer


Sometimes it is difficult to convert objects rpy

to numpy

, but it is much more reliable to convert them to objects python

( list

, tuple

etc.) and build array

later. Decision:



In [33]:

import numpy as np
import rpy2.robjects as robjects
robjects.reval('m1 <- c(1:10)')
robjects.reval("m2 <- matrix(as.complex(m1), nrow=5)")
np.array(list(robjects.r.m2)).reshape(robjects.r.m2.dim)

Out[33]:
array([[  1.+0.j,   2.+0.j],
       [  3.+0.j,   4.+0.j],
       [  5.+0.j,   6.+0.j],
       [  7.+0.j,   8.+0.j],
       [  9.+0.j,  10.+0.j]])

      

+2


source







All Articles