Menu

How to Run an R Script: Rscript, source(), and RStudio

Every way to run R code: the interactive console, Rscript from the command line, source() from inside R, and the Run and Source commands in RStudio.

This page includes runnable editors - edit, run, and see output instantly.

Two Ways to Use R: Console vs Script

R has an interactive console (a REPL - read, evaluate, print, loop): you type an expression, R answers immediately. Typing R in a terminal, or looking at the bottom pane of RStudio, gets you a > prompt where every line runs the moment you press Enter. The console is where you explore - poke at data, test one line, look at the result.

An R script is just a plain text file of R code, saved with a .R extension. Scripts are where analysis lives - a reproducible recipe that anyone (including future you) can run top to bottom and get the same result.

A script is nothing exotic. This is a complete one - run it:

Everything below is about the different ways to feed a file like that to R.

Rscript: Run a File from the Command Line

R installs a command-line tool called Rscript built exactly for this. In a terminal, in the folder containing your file:

Rscript summary.R

R starts, runs the file top to bottom, prints whatever the script prints, and exits. This is the workhorse for automation - cron jobs, data pipelines, servers, CI - anywhere code runs without a human watching.

One behavior surprises everyone once: at the console, typing a bare expression like avg prints its value automatically. Under Rscript, a bare expression inside a function or loop may print nothing - which is why scripts say what they mean with explicit cat() or print() calls. Get in that habit early.

source(): Run a File from Inside R

Already sitting in an R session and want to execute a file? That's source():

source("summary.R")

Every line of the file runs in your current session, and anything the script defines - variables, functions - sticks around afterward. That's the point: source() is how you load your own helper functions into an interactive session.

By default source() runs silently except for explicit output. To watch it work, echo each line as it executes:

source("summary.R", echo = TRUE)

Note the relative path: "summary.R" means "in the current working directory," and where that is depends on how you started R. When source() or read.csv() mysteriously can't find a file that's right there, the working directory is almost always the culprit - see working directory.

Running Scripts in RStudio

RStudio gives you both modes with two commands, and the distinction is worth internalizing:

  • Run (Ctrl+Enter, Cmd+Enter on macOS) - executes the current line or highlighted selection in the console. This is the exploring gear: write a line, run it, look, adjust.
  • Source (the Source button, or Ctrl/Cmd+Shift+S) - executes the entire file, exactly like source() at the console.

The trap with Run-line-by-line is that your console session accumulates state - variables from lines you later edited or deleted are still alive, so the script "works" for you and fails for everyone else. The honest test of a script is Source in a fresh session (Session → Restart R, then Source). If it survives that, it's reproducible.

Making a Script Executable (macOS / Linux)

On Unix-like systems you can turn an R script into a command of its own. Put a shebang line at the very top of the file:

#!/usr/bin/env Rscript
cat("I am a self-running R script\n")

Then mark it executable once, and run it directly:

chmod +x summary.R
./summary.R

The shebang tells the shell which interpreter runs the file; env Rscript finds Rscript wherever it lives on that machine's PATH. Since the line starts with #, R itself reads it as a comment and ignores it.

Passing Arguments to a Script

Real scripts take inputs - a filename, a date, a threshold - passed after the script name:

Rscript report.R sales.csv 2026

Inside the script, commandArgs(trailingOnly = TRUE) returns your arguments as a character vector (trailingOnly = TRUE drops the interpreter's own internal arguments - you virtually always want it):

# report.R
args <- commandArgs(trailingOnly = TRUE)

input_file <- args[1]
year <- as.numeric(args[2])

cat("Reading:", input_file, "\n")
cat("Filtering to year:", year, "\n")

Everything arrives as text - "2026", not 2026 - so convert with as.numeric() before doing math. We can simulate the parsing logic in a runnable form:

Which One Should You Use?

  • Exploring data, trying ideas → the console, or Run in RStudio.
  • Executing your whole analysis → Source in RStudio, or Rscript in a terminal.
  • Loading your helper functions into a sessionsource("helpers.R").
  • Automation, schedulers, pipelinesRscript, with commandArgs() for inputs.

The syntax of what goes inside those files is the next lesson - see R syntax.

What You Take Away

  • The console is for exploring; .R script files are for reproducible analysis.
  • Rscript file.R runs a script from the command line; source("file.R") runs it inside a session (add echo = TRUE to watch).
  • In RStudio, Run executes a line; Source executes the file - and Source-in-a-fresh-session is the real reproducibility test.
  • #!/usr/bin/env Rscript + chmod +x makes a script directly executable; commandArgs(trailingOnly = TRUE) reads its arguments as text.

Next up: R's syntax - assignment with <-, function calls, and the everything-is-a-vector rule.

Frequently Asked Questions

How do I run an R script from the command line?

Use the Rscript command that ships with R: Rscript analysis.R. It runs the file from start to finish and prints anything the script prints. This is the standard way to run R in scheduled jobs, pipelines, and servers.

What is the difference between Run and Source in RStudio?

Run (Ctrl/Cmd+Enter) executes only the current line or selection in the console - ideal while exploring. Source executes the whole file in one go, like Rscript would. Sourcing your script from a clean session is the real test that it works top to bottom.

What does source() do in R?

source("script.R") reads a file and executes every line inside your current R session, so any variables and functions it defines become available to you. Add echo = TRUE to also print each line as it runs.

How do I pass arguments to an R script?

Run Rscript script.R value1 value2, then read them inside the script with args <- commandArgs(trailingOnly = TRUE). The trailingOnly = TRUE part strips the interpreter's own bookkeeping arguments and keeps just yours. Everything arrives as text, so convert numbers with as.numeric().

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED