Calling an R script with command line arguments from Python rpy2

不想你离开。 提交于 2021-02-07 09:12:56

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/29070200/calling-an-r-script-with-command-line-arguments-from-python-rpy2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!