Your First R Script
An R script is a plain text file of commands and comments that R runs from top to bottom, showing only what you print or what is automatically printed at the top level.
Run a saved sequence of expressions and inspect its values and printed output.
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().