Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running an R script from command line (to execute from python)

I'm currently trying to run an R script from the command line (my end goal is to execute it as the last line of a python script). I'm not sure what a batch file is, or how to make my R script 'executable'. Currently it is saved as a .R file. It works when I run it from R.
How do I execute this from the windows command prompt line? Do i need to download something called Rscript.exe? Do I just save my R script as an .exe file? Please advise on the easiest way to achieve this.
R: version 3.3 python: version 3.x os: windows

like image 696
W Anderson Avatar asked Feb 06 '23 09:02

W Anderson


1 Answers

As mentioned, Rscript.exe the automated executable to run R scripts ships with any R installation (usually located in bin folder) and as @Dirk Eddelbuettel mentions is the recommended automated version. And in Python you can run any external program as a subprocess with various types including a call, check_output, check_call, or Popen and the latter of which provides more facility such as capturing errors in the child process.

If R directory is in your PATH environmental variable, you do not need to include full path to RScript.exe but just name of program, Rscript. And do note this is fairly the same process for Linux or Mac operating systems.

command = 'C:/R-3.3/bin/Rscript.exe'          # OR command = 'Rscript'
path2script = 'C:/Path/To/R/Script.R'
arg = '--vanilla'

# CHECK_CALL VERSION
retval = subprocess.check_call([command, arg, path2script], shell=True)

# CALL VERSION
retval = subprocess.call(["'Rscript' 'C:/Path/To/R/Script.R'"])

# POPEN VERSION (W/ CWD AND OUTPUT/ERROR CAPTURE)
curdir = 'C:/Path/To/R/Script'
p = subprocess.Popen(['Rscript', 'Script.R'], cwd=curdir,
                     stdin = subprocess.PIPE, stdout = subprocess.PIPE, 
                     stderr = subprocess.PIPE)            
output, error = p.communicate()

if p.returncode == 0:            
    print('R OUTPUT:\n {0}'.format(output.decode("utf-8")))
else:                
    print('R ERROR:\n {0}'.format(error.decode("utf-8"))) 
like image 156
Parfait Avatar answered Feb 09 '23 01:02

Parfait