Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an R script with command line arguments from Python rpy2

Tags:

python

r

rpy2

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

like image 904
ChrisGuest Avatar asked Jul 30 '26 08:07

ChrisGuest


1 Answers

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.

like image 169
Paul Hiemstra Avatar answered Aug 01 '26 22:08

Paul Hiemstra