Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to execute .R script

Tags:

r

python-2.7

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.

like image 854
Mryan_Pledge Avatar asked Jul 26 '26 01:07

Mryan_Pledge


2 Answers

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.

like image 189
andrewdotn Avatar answered Jul 28 '26 04:07

andrewdotn


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'])
like image 21
Layla Avatar answered Jul 28 '26 05:07

Layla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!