3

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tend to think that I do have a need to pass command line arguments, as I am trying to use scripts that are also used in a standalone capacity.
Please @Paul can you provide an example on the first approach ? Edit : I fail to understand how that uses R language, it seems to me you are advising to create a python function that does the same thing than the R function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.