Logo

How to run R script from command line?

The most straightforward way to run an R script from the command line is via Rscript:

Rscript path/to/your_script.R
  • Make sure you have Rscript in your system’s PATH (this usually comes automatically when R is installed).
  • This command executes your script in a fresh R session, then terminates once it finishes.

Using R CMD BATCH

Another approach uses R CMD BATCH:

R CMD BATCH path/to/your_script.R
  • By default, it creates a .Rout file containing both console output and error messages.
  • Useful if you want to keep logs of your script’s output for later review.

Command Line Arguments

You can also pass arguments to your script. For example:

Rscript path/to/your_script.R arg1 arg2

Inside your script, access them via commandArgs(trailingOnly = TRUE). This way, you can make your script more dynamic by adapting its behavior based on command line inputs.

Best Practices

  • Make sure your script includes all required library calls (e.g., library(dplyr)), because each run is a fresh environment.
  • Use exit codes (e.g., quit(status=1)) to signal success or failure in more advanced scripting.

Strengthen Your Coding & System Design Skills

If you’re expanding your interview or development toolkit, try these courses:

For those aiming to architect scalable systems, consider Grokking System Design Fundamentals. You can also practice with Coding Mock Interviews conducted by ex-FAANG engineers. To explore more tutorials and insights, visit the DesignGurus.io YouTube channel.

CONTRIBUTOR
TechGrind