4

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?

Mannaggia
  • 4,559
  • 12
  • 34
  • 47
  • 1
    Quite possibly a bug. Open an issue on rpy2's tracker on bitbucket. – lgautier Jul 15 '15 at 02:34
  • Can you post the link to the issue? I find converting `rpy` to `np` can be tricky sometimes. Converting `rpy` to `python` buildins and then convert them to `numpy` rescues (see below). Might due to `typestr` not being passed correctly to `numpy` `array` constructor. – CT Zhu Aug 03 '15 at 16:41

1 Answers1

2

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]])
CT Zhu
  • 52,648
  • 17
  • 120
  • 133