如何使用rpy2将numpy数组转换为R矩阵?这可能是微不足道的,但我在文档中找不到一个好的答案。我可以通过首先转换为pandas数据帧作为额外步骤来实现这一点,但这似乎是多余的。
工作示例:
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"])
答案 0 :(得分:3)
这可以根据帖子Converting python objects for rpy2和numpy to rpy2 conversion上的rpy2文档进行操作:
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)