Run R script from command line

ID : 3757

viewed : 140

Tags : rcommand-liner





Top 5 Answer for Run R script from command line

vote vote

91

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.

vote vote

86

This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.

  • To install to the default location:

    R -e 'install.packages(c("package1", "package2"))' 
  • To install to a location that requires root privileges:

    R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")'  
vote vote

74

One more way of running an R script from the command line would be:

R < scriptName.R --no-save   

or with --save.

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

vote vote

66

You need the ?Rscript command to run an R script from the terminal.

Check out http://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html

Example

## example #! script for a Unix-alike  #! /path/to/Rscript --vanilla --default-packages=utils args <- commandArgs(TRUE) res <- try(install.packages(args)) if(inherits(res, "try-error")) q(status=1) else q() 
vote vote

54

How to run Rmd in command with knitr and rmarkdown by multiple commands and then Upload an HTML file to RPubs

Here is a example: load two libraries and run a R command

R -e 'library("rmarkdown");library("knitr");rmarkdown::render("NormalDevconJuly.Rmd")'  R -e 'library("markdown");rpubsUpload("normalDev","NormalDevconJuly.html")' 

Top 3 video Explaining Run R script from command line







Related QUESTION?