Convert numpy matrix to R matrix and keep it that way

752 views Asked by At

I'd like to convert a numpy matrix to R an matrix. I'm aware that you to do this:

from rpy2 import robjects as ro
ro.conversion.py2ri = ro.numpy2ri
ro.numpy2ri.activate()

And then build an R matrix:

mat_r = ro.r.matrix(mat_py)

But the problem is, whenever I refer to the new matrix in python it gets converted back to a numpy matrix. For instance, I need to set the row and column names, but doing that results in this:

mat_r.rownames = numpy.array([1,2,3])
AttributeError: 'numpy.ndarray' object has no attribute 'rownames'

Anyone know how I can keep my shiny new r matrix as an r matrix, and stop is becoming a ndarray again?

1

There are 1 answers

1
lgautier On BEST ANSWER

One way might be

ro.numpy2ri.deactivate()

The conversion can also be called explicitly (the conversion generics are in the module, here numpy2ri).