Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert numpy array to R matrix? [duplicate]

Tags:

python

r

rpy2

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"])
like image 917
fileunderwater Avatar asked Dec 03 '14 23:12

fileunderwater


1 Answers

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)
like image 89
fileunderwater Avatar answered Oct 06 '22 00:10

fileunderwater