使用 Python rpy2 中的命令行参数调用 R 脚本 [英] Calling an R script with command line arguments from Python rpy2
问题描述
我希望能够使用 rpy2 模块从 python 调用 R 文件.我希望能够将参数传递给这些脚本,这些脚本可以由 R 的 commandArgs 函数解释.
所以如果我的 R 脚本 (trivial_script.r
) 看起来像:
print(commandArgs(TRUE))
我的 Python 2.7 脚本如下所示:
<预><代码>>>>导入 rpy2.robjects 作为 robjects>>>script = robjects.r.source('trivial_script.r')如何从 rpy2.robjects 使用参数arg1"、arg2"、arg3"调用它?
我将这两种方法(RPy 与命令行脚本)视为两个独立的部分.如果您使用 RPy,则无需传递命令行参数.您只需创建一个包含要在 R 中运行的功能的函数,然后使用 arg1
、arg2
、arg3
从 Python 调用该函数.
如果您想在 Python 中使用 R 命令行脚本,请查看 subprocess
库 Python.在那里您可以使用以下命令从命令行调用 R 脚本:
导入子流程subprocess.call(['Rscript', 'script.R', arg1, arg2, arg3])
其中 arg1
、arg2
、arg3
是包含要传递给 R 脚本的信息的 Python 对象(例如字符串).
I want to be able to call R files from python using the rpy2 modules. I would like to be able to pass arguments to these scripts that can be interpreted by R's commandArgs function.
So if my R script (trivial_script.r
) looks like:
print(commandArgs(TRUE))
and my Python 2.7 script looks like:
>>> import rpy2.robjects as robjects
>>> script = robjects.r.source('trivial_script.r')
How can I call it from rpy2.robjects with the arguments "arg1", "arg2", "arg3" ?
I see the two approaches (RPy vs command line script) as two seperate parts. If you use RPy there is no need to pass command line arguments. You simply create a function that contains the functionality you want to run in R, and call that function from Python with arg1
, arg2
, arg3
.
If you want to use a R command line script from within Python, have a look at the subprocess
library in Python. There you can call and R script from the command line using:
import subprocess
subprocess.call(['Rscript', 'script.R', arg1, arg2, arg3])
where arg1
, arg2
, arg3
are python objects (e.g. strings) that contain the information you want to pass to the R script.
这篇关于使用 Python rpy2 中的命令行参数调用 R 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!