Skip to course content
Free R data course

R Foundations for Data Analysis

Unit 01.01: The console forgets; the script remembers

You will meet four things in the first hour: an editor, a console, a script, and a Quarto document. Only two of them keep your work.

Editors are interchangeable; the console and the script are not

RStudio, Positron and VS Code are all editors. They differ in comfort, not capability, and code written in one runs unchanged in another. Pick one and stop thinking about it.

The distinction that does matter is between the console and a script. The console runs a line and forgets it. A script is a file: it runs top to bottom, survives a restart, and can be sent to somebody. A Quarto document is a script with prose around it, so the explanation and the code that produced the number live in one file and are published together.

Use the console for questions you are about to throw away โ€” what type is this, how many rows. Use a script for anything you would be annoyed to lose.

This block defines a function and runs it twice on the same input.


# A script is a record. The console is not.
# This is what "the same code, run twice, gives the same answer" looks like.

analyse <- function(x) {
  c(n = length(x), mean = mean(x), sd = sd(x))
}

measurements <- c(4.1, 4.8, 5.2, 4.4, 5.0, 4.6)

first_run  <- analyse(measurements)
second_run <- analyse(measurements)

print(round(first_run, 3))
cat("\nIdentical on re-run:", isTRUE(all.equal(first_run, second_run)), "\n")

# What the console cannot tell you afterwards:
cat("Objects currently defined:", paste(sort(ls()), collapse = ", "), "\n")
cat("R version used:", R.version.string, "\n")

Both runs return n = 6, mean = 4.683 and sd = 0.402, and the equality check prints TRUE. That is unremarkable here and is the whole point: a script cannot drift between runs, because there is nothing in it that depends on what you typed earlier. The listing of defined objects โ€” analyse, first_run, measurements, second_run โ€” is the complete state, and all four came from the file.

The mistake this prevents

The mistake is building an analysis in the console over an afternoon and only then copying it into a script. What you copy is the lines that worked, in the order you happen to scroll past them, and it usually will not run start to finish. Write into the file from the beginning.

Takeaway

Editor choice is preference. Console versus script is not: the console is for throwaway questions, the script is the work. Restart R and re-run the file often, so you find out early if it only worked by accident.