python - How to convert an R complex matrix into a numpy array using rpy2 -
it clear me how convert float / double r-matrix numpy array, error if matrix is complex.
example:
import numpy np import rpy2.robjects 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 following line of code:
tmp=np.array(m2) all works fine if matrix not complex:
m2 = robjects.r.matrix(m1, nrow=5) tmp=np.array(m2) thanks help!
ps: note following dirty trick solves problem, not answer question:
tmp=np.array(robjects.r.re(m2))+1j*np.array(robjects.r.im(m2)) ps2: seems nobody can answer question, should conclude there bug in rpy2?
sometimes can become tricky convert rpy objects numpy, more reliable convert them python objects (list, tuple etc) first , construct array later. solution :
in [33]: import numpy np import rpy2.robjects 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]])
Comments
Post a Comment