python - 问题在 Python 中运行程序 (R) 以执行操作(执行脚本)

标签 python r subprocess os.system rpy2

我打算从 python 执行 R 脚本,理想情况下显示和保存结果。使用 rpy2 有点困难,所以我想直接调用 R。我感觉我需要使用“os.system”或“subprocess.call”之类的东西,但我在解读模块指南时遇到困难。

这是 R 脚本“MantelScript”,它使用特定的统计测试一次比较两个距离矩阵(distmatA1 和 distmatB1)。这在 R 中有效,尽管我还没有放入迭代位以便以成对的方式通读和比较一堆文件(我真的需要一些帮助,顺便说一句! ):

library(ade4)

M1<-read.table("C:\\pythonscripts\\distmatA1.csv", header = FALSE, sep = ",")
M2<-read.table("C:\\pythonscripts\\distmatB1.csv", header = FALSE, sep = ",")

mantel.rtest(dist(matrix(M1, 14, 14)), dist(matrix(M2, 14, 14)), nrepet = 999)

这是我的 python 脚本的相关部分,它读取一些先前制定的列表并提取矩阵,以便通过此 Mantel 测试比较它们(它应该从 identityA 中提取第一个矩阵,然后依次将它与 identityB 中的每个矩阵进行比较,然后用 identityB 等的第二个矩阵重复)。我想保存这些文件,然后调用 R 程序来比较它们:

# windownA and windownB are lists containing ascending sequences of integers
# identityA and identityB are lists where each field is a distance matrix.

z = 0
v = 0

import subprocess
import os

for i in windownA:                              

    M1 = identityA[i]                          

    z += 1
    filename = "C:/pythonscripts/distmatA"+str(z)+".csv"
    file = csv.writer(open(filename, 'w'))
    file.writerow(M1)


    for j in windownB:                          

        M2 = identityB[j]                     

        v += 1
        filename2 = "C:/pythonscripts/distmatB"+str(v)+".csv"
        file = csv.writer(open(filename2, 'w'))
        file.writerow(M2)

        ## result = os.system('R CMD BATCH C:/R/library/MantelScript.R') - maybe something like this??

        ## result = subprocess.call(['C:/R/library/MantelScript.txt'])  - or maybe this??

        print result
        print ' '

最佳答案

如果你的 R 脚本只有副作用,那很好,但如果你想用 Python 进一步处理结果,你仍然最好使用 rpy2。

import rpy2.robjects
f = file("C:/R/library/MantelScript.R")
code = ''.join(f.readlines())
result = rpy2.robjects.r(code)
# assume that MantelScript creates a variable "X" in the R GlobalEnv workspace
X = rpy2.rojects.globalenv['X']

关于python - 问题在 Python 中运行程序 (R) 以执行操作(执行脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3339147/

相关文章:

在大型数据集上将 Spark DataFrame 从长到宽 reshape

r - Leaflet Shiny 标记弹出窗口中的格式问题

python - 关闭管道 python 子进程的标准输出

python - "min() arg is an empty sequence"尝试将我的 Pandas plotly 转换为 plotly 时

python - 如何获取对象的根/父类?

r - 在 R 中循环以读取许多文件

python - ssh 与 Subprocess.popen

java - 当我的 Java 应用程序退出/崩溃时,如何摆脱 Java 子进程?

python - 使用 BeautifulSoup 查找具有特定子元素的元素

python - NoReverseMatch 与 Python 社交身份验证/Facebook 登录