0

I have an R script that outputs a CSV that I would like to run in Python.

For example, lets say the R script simply creates a dataframe and outputs a CSV file to my desktop.

sample.r

x <- c(1,2,4)
y <- c("A","B","C")
z <- data.frame(x,y)
write.csv(z,"c:/users/username/dekstop/z.csv)

I'm wondering how I can call the R script in Python in order to create the output.

I have tried utilizing the function below, however it did not create the CSV file.

import subprocess
subprocess.call ("/usr/bin/Rscript --vanilla path/sample.r", shell=True)

Any help is appreciated.

Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
Leo
  • 86
  • 1
  • 6
  • Have you tried [this](https://stackoverflow.com/questions/19894365/running-r-script-from-python) approach? – Kyrylo Feb 26 '18 at 19:23
  • 1
    @ArtemSokolov I think this questions are different because here OP wants to use subprocess instead of rpy2 external python library. – Kyrylo Feb 26 '18 at 19:27
  • What did it create? It looks like the R script has a syntax error (unclosed quote in string path literal) and your Python call is not showing error output. – Parfait Feb 26 '18 at 20:45
  • @Kyrylo: You are right. It's a closer duplicate of the question you linked instead. – Artem Sokolov Feb 26 '18 at 22:10

1 Answers1

0

There are a number of methods you can use to do that. But I think making an R file to a proper executable will solve it not only for python but for other languages. So install fantastic docopt for R which makes it easy to both specify command-line arguments and implement them and make a file like this:

#!/usr/bin/env Rscript

require(docopt)
'Usage:
    test.R [-o <output>]

Options:
    -o Output file [default: sim_data.csv]

 ]' -> doc

 opts <- docopt(doc)

 x <- c(1,2,4)
 y <- c("A","B","C")
 z <- data.frame(x,y)
 write.csv(z, opts$o)

Save the file as test.R and make it executable (Unix/Linux):

chmod +x test.R

From command like run it

./test.R -o path/to/save.csv

See help

./test.R -h

From Python

import os
cmd = './test.R -o path/to/save.csv'
os.system(cmd)
Aleh
  • 776
  • 7
  • 11