您可以在另外两个Stack Overflow问题/答案中找到解决方案:这显示了如何从RData文件加载变量,这显示了如何将R矩阵转换为numpy数组.
结合起来,解决方案看起来像这样:
import rpy2.robjects as robjects
import numpy as np
# load your file
robjects.r['load']('fname.RData')
# retrieve the matrix that was loaded from the file
matrix = robjects.r['fname']
# turn the R matrix into a numpy array
a = np.array(matrix)
print a
Run Code Online (Sandbox Code Playgroud)
例如,如果你开始在R中运行以下代码:
fname <- matrix(1:9, nrow = 3)
save(fname, file = "fname.RData")
Run Code Online (Sandbox Code Playgroud)
上面的Python代码将打印:
[[1 4 7]
[2 5 8]
[3 6 9]]
Run Code Online (Sandbox Code Playgroud)