使用来自Python rpy2的命令行参数调用R脚本

时间:2022-03-15 03:55:59

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.

我希望能够使用rpy2模块从python调用R文件。我希望能够将参数传递给这些脚本,这些脚本可以被R的commandArgs函数解释。

So if my R script (trivial_script.r) looks like:

如果我的R脚本(trivial_script.r)是这样的:

print(commandArgs(TRUE))

and my Python 2.7 script looks like:

我的Python 2。7脚本如下:

>>> 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" ?

如何从rpy2调用它。有参数"arg1", "arg2", "arg3" ?

1 个解决方案

#1


2  

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.

我将两种方法(RPy vs命令行脚本)看作两个分离的部分。如果使用RPy,则不需要传递命令行参数。您只需创建一个包含要在R中运行的功能的函数,并使用arg1、arg2、arg3从Python调用该函数。

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:

如果您想使用Python内部的R命令行脚本,请查看Python中的子过程库。在那里,您可以使用以下命令行调用和R脚本:

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.

arg1、arg2、arg3都是python对象(例如字符串),其中包含要传递给R脚本的信息。

#1


2  

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.

我将两种方法(RPy vs命令行脚本)看作两个分离的部分。如果使用RPy,则不需要传递命令行参数。您只需创建一个包含要在R中运行的功能的函数,并使用arg1、arg2、arg3从Python调用该函数。

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:

如果您想使用Python内部的R命令行脚本,请查看Python中的子过程库。在那里,您可以使用以下命令行调用和R脚本:

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.

arg1、arg2、arg3都是python对象(例如字符串),其中包含要传递给R脚本的信息。