rpy2: Convert FloatVector or Matrix back to a Python array or list?

Question:

I’m using rpy2 and I have this issue that’s bugging me: I know how to convert a Python array or list to a FloatVector that R (thanks to rpy2) can handle within Python.

Can the opposite can be done? For example, I have a FloatVector or Matrix that is an R object. How can I convert it back to a Python array or list?

Asked By: Néstor

||

Answers:

Found the answer myself :-). Suppose vector_R is a FloatVector. To convert it back to Python you need to do:

import rpy2.robjects.numpy2ri as rpyn
vector=rpyn.ri2numpy(vector_R)

And that’s it! “vector” is now a Numpy array.

Answered By: Néstor

This worked like a charm:

vector=numpy.asarray(vector_R)
Answered By: AnirudhJ

In the latest version of rpy2, you can simply do this in a direct way:

import numpy as np
array=np.array(vector_R)
Answered By: Jeremy Z
import rpy2.robjects.numpy2ri as rpyn
vector=rpyn.ri2py(v)

Does it in the new rpy2, where v is the vector

Answered By: Mazi WIzi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.