Mryan_Pledge
Mryan_Pledge

Reputation: 63

Using python to execute .R script

After seven hours of googling and rereading through somewhat similar questions, and then lots of trial and error, I'm now comfortable asking for some guidance.

To simplify my actual task, I created a very basic R script (named test_script):

x <- c(1,2,3,4,5)
avg <- mean(x)
write.csv(avg, file = "output.csv")

This works as expected.

I'm new to python and I'm just trying to figure out how to execute the R script so that the same .csv file is created.

Notable results come from:

subprocess.call(["C:/Program Files/R/R-2.15.2/bin/R", 'C:/Users/matt/Desktop/test_script.R'])

This opens a cmd window with the typical R start-up verbiage, except there is a message which reads, "ARGUMENT 'C:/Users/matt/Desktop/test_script.R' __ ignored __"

And:

subprocess.call(['C:/Program Files/R/R-2.15.2/bin/Rscript', 'C:/Users/matt/Desktop/test_script.r'])

This flashes a cmd window and returns a 0, but no .csv file is created.

Otherwise, I've tried every suggestion I could identify on this site or any other. Any insight will be greatly appreciated. Thanks in advance for your time and efforts.

Upvotes: 3

Views: 4676

Answers (2)

Layla
Layla

Reputation: 453

It might be too late, but hope it helps for others:

Just add --vanilla in the call list.

subprocess.call(['C:/Program Files/R/R-2.15.2/bin/Rscript',  '--vanilla', 'C:/Users/matt/Desktop/test_script.r'])

Upvotes: 1

andrewdotn
andrewdotn

Reputation: 34813

Running R --help at the command prompt prints:

Usage: R [options] [< infile] [> outfile]
   or: R CMD command [arguments]

Start R, a system for statistical computation and graphics, with the
specified options, or invoke an R tool via the 'R CMD' interface.

Options:
  -h, --help            Print short help message and exit
  --version             Print version info and exit
  ...
  -f FILE, --file=FILE  Take input from 'FILE'
  -e EXPR               Execute 'EXPR' and exit

FILE may contain spaces but not shell metacharacers.

Commands:
  BATCH         Run R in batch mode
  COMPILE       Compile files for use with R
  ...

Try

call(["C:/Program Files/R/R-2.15.2/bin/R", '-f', 'C:/Users/matt/Desktop/test_script.R'])

There are also some other command-line arguments you can pass to R that may be helpful. Run R --help to see the full list.

Upvotes: 3

Related Questions