Home Content Running an R script through Python

Running an R script through Python

by Jack Simpson

Before I made the switch to developing on a Linux machine, I noticed that the Python module for calling R (RPy2) seemed to be having some problems on Windows. This gave me an excuse to play around with writing my own Python script to create and run an R script. As you’ll see in the code below, I’ve used the subprocess module to execute the R script I created and then pipe the results back into the terminal.

import subprocess

# rscript is the content of the R file we'll create
rscript = '''#!/usr/bin/Rscript

cat('This is a simple program') # same as c()
NumOfIterations for (i in 1:NumOfIterations) { # 1:10 is range
cat(i, 'Hello world!')
cat(' ')
}
'''
r_file = open("example.r", "w")
r_file.write(rscript)
r_file.close()

r_file_name = "example.r"
ppath = r'C:Program FilesRR-2.15.2bini386Rscript.exe'
proc = subprocess.Popen("%s %s" % (ppath, r_file_name), stdout=subprocess.PIPE)
output = proc.stdout.read()
print output

Sign up to my newsletter

Sign up to receive the latest articles straight to your inbox

You may also like

Leave a Comment