我试图从python执行R脚本,理想地显示并保存结果。使用rpy2已经有点困难了,所以我想我会直接调用R。我有一种感觉,我需要使用诸如“os.system”或“subprocess.call”之类的东西,但我很难破译模块指南。问题在Python中运行程序(R)以执行操作(执行脚本)
这是R脚本“MantelScript”,它使用特定的统计测试来比较两个距离矩阵(distmatA1和distmatB1)。这在R中有效,尽管我还没有放入迭代位以读取和比较一堆文件(,我真的需要一些帮助,太btw了!)::
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保存.csv文件之后执行它,因为我有时间限制。该代码仍然存在一个问题,但是(作为“外行”)发现它更容易处理。 – user393200 2010-07-28 15:01:46
@ vehicularlambslaughter.myopenid.c:“发现它更容易处理”这也是我的看法。一个程序写文件而另一个程序读文件的简单管道是最好的。用“子过程”欺骗太多通常不会有帮助。 – 2010-07-28 18:22:17