How to convert numpy array to R matrix?

python, r, rpy2

Solution

This works, based on the post Converting python objects for rpy2 and the rpy2 documentation on numpy to rpy2 conversion:

import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()

nr,nc = B.shape
Br = ro.r.matrix(B, nrow=nr, ncol=nc)

ro.r.assign("B", Br)

Problem

How do you convert a numpy array to a R matrix using rpy2? This might be trivial, but I cannot find a good answer in the documentation. I can get this working by first converting to a pandas dataframe as an extra step, but this seems redundant. Working example: ``` import numpy as np from pandas import * import pandas.rpy.common as com import rpy2.robjects as ro B=np.array([[1,2,3],[4,5,6],[7,8,9]]) Rmatrix = com.convert_to_r_matrix(B) # Does not work #Extra conversion via pandas dataframe PandasDF = DataFrame(B) Rmatrix = com.convert_to_r_matrix(PandasDF) ro.r.assign("Bmatrix", Rmatrix) print(ro.r["Bmatrix"]) ```

Original source

Related problems