Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an R complex matrix into a numpy array using rpy2

Tags:

python

r

numpy

rpy2

it is clear to me how to convert a float / double R-matrix into 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)

All works fine if the matrix is not complex:

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 does not really answer the question:

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

PS2: it seems that nobody can answer this question, should we conclude there is a bug in rpy2?

like image 368
Mannaggia Avatar asked Sep 19 '25 04:09

Mannaggia


1 Answers

Sometimes it can become tricky to convert rpy objects to numpy, but it is much more reliable to convert them to python objects (list, tuple etc) first and construct an array later. A solution :

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]])
like image 120
CT Zhu Avatar answered Sep 21 '25 19:09

CT Zhu