Your First R Script
An R script is simply a plain text file with a .R extension containing a sequence of R commands, which you can execute line by line interactively in the RStudio Console, run as a whole with the source() function, or execute from a terminal with Rscript myscript.R. Unlike typing directly into the Console, saving your work as a script means every step of your analysis is reproducible — you or a colleague can rerun the exact same file later and get the exact same result, which is the foundation of reproducible data analysis.
Cricket analogy: A saved .R script is like a documented match strategy handed to every player before play, versus a captain shouting instructions on the fly — anyone can rerun the same plan (source() the file) and get the same tactical outcome every time.
Writing the Script: Variables and Basic Operations
A typical first script starts by creating some data, performing a calculation, and printing a result — for example storing exam scores in a vector, computing the class average, and printing it with a labeled message. Comments start with # and are ignored by R entirely, so it's good practice to comment why a step exists, not just what it does, since the code itself already shows the 'what.' Note that at the top level of the Console, R auto-prints the result of any expression that isn't assigned, but inside a sourced script, a function, or a loop, nothing auto-prints — you must call print() or cat() explicitly to see output.
Cricket analogy: Commenting why (not what) a line does is like a coach's notebook explaining 'switched the batting order because of the short boundary' rather than just 'Kohli now batting at 3' — the reasoning is the useful part, since the action is already visible.
Adding a Function and Control Flow
A script becomes genuinely useful once it includes a custom function — defined with function(arguments) { body } and assigned to a name — combined with control flow like if/else for branching and a for loop for repetition. For example, a function grade_report(score) can use if (score >= 90) to classify a grade, and a for (student in names) loop can call that function once per student in a vector, printing a personalized line for each; R also supports the vectorized alternative ifelse() for simple element-wise branching without an explicit loop.
Cricket analogy: A custom function like grade_report() is like a standard net-practice drill a coach runs identically for every batter in the squad, while the for loop is like cycling every player from the squad list through that same drill one by one.
Running the Script
Inside RStudio, you can execute the whole file with the 'Source' button (or Ctrl+Shift+Enter), which runs every line top to bottom as if pasted into the Console, or highlight and run just a portion with Ctrl+Enter to debug interactively. Outside RStudio, running Rscript path/to/myscript.R from a terminal executes the file non-interactively — useful for scheduling a script to run automatically (e.g., via cron on Linux/macOS or Task Scheduler on Windows) without opening RStudio at all, which is exactly how R scripts get deployed in automated reporting pipelines.
Cricket analogy: Running the whole script with 'Source' is like playing a full completed match from ball one, while Ctrl+Enter on a highlighted section is like replaying just one contentious over for review — and Rscript from the terminal is like a scheduled TV broadcast airing automatically without a studio host present.
# my_first_script.R
# Goal: summarize exam scores and print a per-student grade report
scores <- c(Alice = 92, Bilal = 74, Chen = 88, Divya = 55)
class_average <- mean(scores)
cat("Class average:", round(class_average, 1), "\n")
# A reusable function to turn a numeric score into a letter grade
grade_report <- function(score) {
if (score >= 90) {
"A"
} else if (score >= 75) {
"B"
} else if (score >= 60) {
"C"
} else {
"F"
}
}
# Loop over every student and print their grade
for (student in names(scores)) {
grade <- grade_report(scores[[student]])
cat(student, "scored", scores[[student]], "->", grade, "\n")
}
# Run this whole file from a terminal with:
# Rscript my_first_script.Rcat() and print() serve different purposes: print() shows an object using R's formatted, type-aware display (useful for inspecting data frames or vectors), while cat() concatenates and prints plain text with no quotes or index markers, which is usually what you want for a human-readable status message or report line.
Expressions only auto-print at the top level of an interactive Console session. The same expression typed inside a function, a for loop, or a script run via source() or Rscript will produce no visible output unless you explicitly wrap it in print() or cat() — a very common source of 'my script ran but nothing showed up' confusion for beginners.
- An R script is a plain .R text file of commands, runnable via Console, source(), or Rscript from a terminal.
- Saving work as a script (rather than typing only in the Console) makes analysis reproducible.
- Comments start with # and should explain why a step exists, not just restate what the code does.
- Auto-printing only happens at the Console's top level; inside functions, loops, or sourced scripts, use print()/cat() explicitly.
- Custom functions are defined with function(args) { body } and combined with if/else and for loops for real logic.
- ifelse() offers a vectorized alternative to if/else for simple element-wise branching.
- Rscript myscript.R runs a script non-interactively from the terminal, enabling scheduled/automated execution.
Practice what you learned
1. What is the main advantage of saving R code as a .R script instead of typing only in the Console?
2. Why might an expression that works fine in the Console produce no visible output inside a for loop in a sourced script?
3. How do you run an R script named report.R from a terminal, outside of RStudio?
4. What is the difference between cat() and print() in R?
5. What does ifelse() provide that a standard if/else does not?
Was this page helpful?
You May Also Like
R Operators
A tour of R's arithmetic, relational, logical, and special operators, including vectorized behavior and common pitfalls like && vs &.
R Variables and Data Types
How to create variables in R with the assignment operator, the core atomic data types, special values like NA and NULL, and how type coercion works.
Installing R and RStudio
How to install R and RStudio Desktop, understand the difference between them, and navigate the RStudio IDE for the first time.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics