Calling R scripts from Python

01 Aug 2017 -

Packages like rpy2 make it easy to use R functions and objects within Python. For longer blocks of code, though, it may be easier to work within an R IDE like RStudio and to call the whole script from within Python.

I needed to call an entire R script from within Python recently and found that it wasn’t straightforward to find instructions for doing so online. So here’s a simple explanation of how to get your R scripts to run from within Python.

First, you’ll need the subprocess package.

import subprocess

Then, you’ll need to construct a command to run. This consists of three elements: first, the location of your R interpreter; second, the option –vanilla; and third, the location of your R script. Note that I use Microsoft R Open and Windows. Your R interpreter may be located somewhere slightly different, but should be located within the bin folder wherever R is stored.

command = ("C:/Program Files/Microsoft/MRO-3.3.2/bin/Rscript.exe " "--vanilla D:/ndhen/Dropbox/Sample/foo.R")

Next, run the script. We have a few options. If you want the R script to run without returning to Python, you can use

subprocess.Popen(command)

If you need to continue running the Python script after the R script finishes, the following command will pause the execution in Python until after the R script is finished.

subprocess.Popen(command).wait()

And if you need to use the output of an R script within Python, you can do so by using

variable_name = subprocess.check_output(command)

So the final code, assuming we want to come back to Python looks like this:

import subprocess command = ("C:/Program Files/Microsoft/MRO-3.3.2/bin/Rscript.exe " "--vanilla D:/ndhen/Dropbox/Sample/foo.R") subprocess.Popen(command).wait()