我的问题似乎很基本,但即使在rpy2文档上我也找不到答案。我有* .R脚本接受一个参数为“file.txt”(我需要传递参数而不是命令行)。我想在python脚本中调用R脚本。我的问题是:如何传递和恢复R脚本的参数?我的解决方案是:假设R脚本是从这一行开始的:
df <- read.table(args[1], header=FALSE)
"
here args[1] should be the file which is not passed from the command line
"
....
现在我在我的python脚本中编写一个函数:
from rpy2 import robjects as ro
def run_R(file):
r = ro.r
r.source("myR_script.R")
# how to pass the file argument to
# the R script and how to
# recuperate this argument in the R code?
我的问题似乎很基本,但即使在rpy2文档上我也找不到答案。
这可能是一个很好的起点:
(...)
df <- read.table(args[1], header=FALSE) " here args[1] should be the file which is not passed from the command line "
当你到达那里时,命令行的参数很久就传递给了R(因为R已经初始化并且在那时已经运行)。文档中的上述链接将是一种相对优雅的解决方法。否则你总是可以在R中创建一个矢量args
:
rpy2.robjects.globalenv['args'] = robjects.vectors.StrVector(['my_file.csv'])
r.source("myR_script.R")
为什么只使用rpy2
来运行R脚本?考虑避免使用这个接口,而是使用自动化的Rscript.exe
命令行,Python可以使用内置的subprocess
调用,就像任何外部可执行文件一样,即使在传递所需的参数时也是如此。
下面假设您在PATH环境变量中有R bin文件夹来识别Rscript
。如果没有,请在cmd的第一个arg中添加此可执行文件的完整路径。另外,请务必将文件的完整路径传递给run_R方法:
from subprocess import Popen, PIPE
def run_R(file):
# COMMAND WITH ARGUMENTS
cmd = ["Rscript", "myR_script.R", file]
p = Popen(cmd, cwd="/path/to/folder/of/my_script.R/"
stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
# PRINT R CONSOLE OUTPUT (ERROR OR NOT)
if p.returncode == 0:
print('R OUTPUT:\n {0}'.format(output))
else:
print('R ERROR:\n {0}'.format(error))