How to Run an R Script from the Command Line

I’m writing this post because I just spent a couple of hours banging my head against the wall, trying to figure out how to run an R script from the command line. It was working if I simply ran it at the command line. But when I try to run the same command from Java (I know, this sounds convoluted) using the following code, it was behaving strangely and wasn’t executing.

Runtime r = Runtime.getRuntime();
r.exec("R CMD BATCH RScriptFile.R");

So I finally found out that there is a utility in R that is designed to help you execute scripts at the command line more easily. It’s called RScript. Now I’m doing it the following way, and it’s working beautifully.

Runtime r = Runtime.getRuntime();
r.exec("Rscript RScriptFile.R");

Seems obvious, but it wasn’t to me, and it took awhile to find an answer.

6 Responses to “How to Run an R Script from the Command Line”

  1. Really appreciate your help…

  2. You can also use Rscript and insert bash variable interpolation

    $ z=10
    $ echo $z
    10
    $ Rscript -e “x=1:$z;sd(x);mean(x)”
    [1] 3.027650
    [1] 5.5
    $

    and bash shell will interpolate the double quotes,
    and send the R commands, x=1:10;sd(x);mean(x) to R
    for processing and the output will appear in STDOUT

  3. Hey, great post! Just what I needed while I was trying to cron my first R script :) !

  4. Yes I might add that the Rscript interface makes for a much easier ride for passing in command line arguements in R!

    RScript myscript.R arguement1 arguement2 arguement3

    I agree, I spent a while looking for this (which seems obvious). Shame that the documentation for a lot of R functionality really lags behind.

  5. Hi! Great post! But..for me it’s still not working. I did just as you said. Do you have any idea about why this is hapenning?

  6. What command are you executing? What error message are you getting? What operating system are you running?

Leave a Reply