问题
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