Your First R Script
Typing into the console is fine for a quick sum, but next week you will want to run the same harvest summary again with new numbers. A script saves your steps in a file, so you can rerun them, fix them and share them.
The rule
A script is a saved conversation with the console, run top to bottom.
A script is a plain text file whose name ends in .R. R reads it line by line, from the first line to the last, much as if you had typed each line at the > prompt.
# harvest.R — summarise this week's garden harvest
kg <- c(12.5, 8, 15, 3.5, 6) # kilograms from plots A to E
total <- sum(kg)
cat("Total harvest:", total, "kg\n")
print(mean(kg))Comments start with #. R ignores everything from the # to the end of that line, so a comment can sit on its own line or after code. R has no block-comment syntax: for several lines, start each one with # (in RStudio, select the lines and press Ctrl+Shift+C, or Cmd+Shift+C on a Mac). Use comments to say why, not to repeat what the code already says.
Output comes from two everyday functions:
print(x)shows a value the way the console does, with the[1]label:[1] 9.cat(...)writes plain text: no quotes, no[1], pieces separated by spaces, and no line break unless you add"\n".
Three ways to run it:
- In an editor, put the cursor on a line and press Ctrl+Enter (Cmd+Enter on a Mac) to send that line to the console.
- At the console,
source("harvest.R")runs the whole file. - In a terminal,
Rscript harvest.Rruns it without opening an editor.
One difference catches everyone. At the console, and with Rscript, a bare value such as total on its own line is printed automatically. With source(), and inside loops and functions, nothing is printed unless you call print() or cat().
The shortcut
Read a script the way R does: one line at a time, top to bottom, skipping everything after a #. Assignments are silent; only printing puts something on the screen.
The first line
A comment. R skips it entirely.
When a script "does nothing", check whether you are relying on automatic printing. Wrapping the value in print() works everywhere.
Drills
Answer fast — trust the rule.
What does R do with the line kg <- c(1, 2) # two plots?
How do you write a comment that spans three lines?
Which command runs harvest.R from a terminal?
What does cat("Total:", 45, "kg\n") print?
A script run with source("harvest.R") ends with the bare line total. What appears?
Remember
- A script is a saved conversation with the console, run top to bottom.
- Shortcut: read it like R does. Skip comments, assignments are silent, only printing shows.
- Trap:
source()(by default), loops and functions do not auto-print, so useprint()orcat().
