100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Your First R Script

How to write, structure, and run a complete R script covering variables, a custom function, control flow, and output, both inside RStudio and from the command line.

FoundationsBeginner9 min readJul 10, 2026
Analogies

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.

r
# 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.R

cat() 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

Was this page helpful?

Topics covered

#Programming#RProgrammingStudyNotes#YourFirstRScript#Script#Writing#Variables#Operations#StudyNotes#SkillVeris#ExamPrep