我的问题似乎很基本,但即使在 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
"
....
Run Code Online (Sandbox Code Playgroud)
现在我在我的 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?
Run Code Online (Sandbox Code Playgroud)
为什么rpy2只用于运行 R 脚本?考虑避免使用此接口,而是使用Rscript.exePython 可以subprocess像任何外部可执行文件一样内置调用的自动化命令行,即使在传递所需参数时也是如此。
下面假设您在 PATH 环境变量中有 R bin 文件夹来识别Rscript. 如果没有,请在cmd 的第一个参数中添加此可执行文件的完整路径。另外,请务必将文件的完整路径传递给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))
Run Code Online (Sandbox Code Playgroud)
我的问题似乎非常基本,但即使在 rpy2 文档中我也找不到答案。
但这可能是一个很好的起点:
https://rpy2.github.io/doc/v3.0.x/html/robjects_rpackages.html#importing-任意-r-code-as-a-package
(...)
Run Code Online (Sandbox Code Playgroud)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")
Run Code Online (Sandbox Code Playgroud)