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.

4
  • Have you tried this approach? Commented Feb 26, 2018 at 19:23
  • 1
    @ArtemSokolov I think this questions are different because here OP wants to use subprocess instead of rpy2 external python library. Commented Feb 26, 2018 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. Commented Feb 26, 2018 at 20:45
  • @Kyrylo: You are right. It's a closer duplicate of the question you linked instead. Commented Feb 26, 2018 at 22:10

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.