如何使用 rpy2 访问 Python 中的 .Rdata 文件中的矩阵

How to access a matrix in an .Rdata file in Python using rpy2

我有很多 saved R datasets(尽管它们有 .R 个扩展名)。我可以使用 R 使用 load("fname.R") 访问这些矩阵之一 fname.R,然后输入文件名 fname

不过,我想在Python中使用这个矩阵。我可以使用 rpy2 来导入数据,但我也有兴趣处理这些数据。我怎样才能把它变成一个 Python 矩阵?

您可以在其他两个 Stack Overflow questions/answers 中找到解决方案:this shows how to load a variable from an RData file, and this shows how to convert an R matrix to a numpy array

结合起来,解决方案如下所示:

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

例如,如果您通过 运行 R 中的以下代码启动:

fname <- matrix(1:9, nrow = 3)
save(fname, file = "fname.RData")

上面的 Python 代码将打印:

[[1 4 7]
 [2 5 8]
 [3 6 9]]