What's the Best Way to Use R Scripts on the Command Line (Terminal)

Run R script from command line

If you want the output to print to the terminal it is best to use Rscript

Rscript a.R

Note that when using R CMD BATCH a.R that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.

R CMD BATCH a.R
# Check the output
cat a.Rout

One other thing to note about using Rscript is that it doesn't load the methods package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.

If you really want to use the ./a.R way of calling the script you could add an appropriate #! to the top of the script

#!/usr/bin/env Rscript
sayHello <- function(){
print('hello')
}

sayHello()

I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.

What's the best way to use R scripts on the command line (terminal)?

Content of script.r:

#!/usr/bin/env Rscript

args = commandArgs(trailingOnly = TRUE)
message(sprintf("Hello %s", args[1L]))

The first line is the shebang line. It’s best practice to use /usr/bin/env Rscript instead of hard-coding the path to your R installation. Otherwise you risk your script breaking on other computers.

Next, make it executable (on the command line):

chmod +x script.r

Invocation from command line:

./script.r world
# Hello world

Running R Code from Command Line (Windows)

  1. You want Rscript.exe.

  2. You can control the output from within the script -- see sink() and its documentation.

  3. You can access command-arguments via commandArgs().

  4. You can control command-line arguments more finely via the getopt and optparse packages.

  5. If everything else fails, consider reading the manuals or contributed documentation

Run Rscript interactive (readline()) in Command-line

Instead of asking, you can pass arguments, parameters, to the script.

Instead of

scrpt.R:

r=readline(prompt="number: ")
print(sqrt(r))

You can do

scrpt.R:

args<-commandArgs(TRUE)
print(sqrt(as.numeric(args[1])))

And at the command window,

c:\R\ax>Rscript scrpt.R 2 arg2 arg3
[1] 1.414214


Related Topics



Leave a reply



Submit