R Programming / Language and data foundations / Lesson 1
Scripts, objects, and session boundaries
Build a reproducible base-R calculation whose inputs and assumptions are visible in one script.
On this page
Lesson goals
- Distinguish expressions, assignment, and object inspection.
- Keep calculations independent of hidden workspace state.
- Choose explicit input and output boundaries.
R evaluates expressions and produces objects
R is a language for computation as well as an interactive statistical environment. An expression can return a value, create an object through assignment, or perform a side effect such as drawing a plot. Names are case-sensitive, and <- is a familiar assignment operator in scripts. An interactive console is useful for exploration, but a calculation that works only after an undocumented sequence of commands is difficult to review. Write a script that creates its own tiny inputs and names intermediate results according to their meaning and units. A successful console command is evidence about one session, not automatically a reproducible procedure.
A vector result has a type and a length
The first fixture constructs three numeric durations and computes their mean. R arithmetic is naturally vector-oriented, so c(10,20,30) is one vector rather than three unrelated scalar variables. Inspect type, length, names, and dimensions when learning a new function. R may print returned values automatically at an interactive prompt, while scripts should use explicit output when a result must be visible. The program uses cat to control the displayed line rather than relying on vector-printing spacing. Its assertion expresses an important contract: computing a summary should not unexpectedly alter the supplied measurements.
minutes <- c(10, 20, 30)
mean_minutes <- mean(minutes)
cat("count=", length(minutes), "; mean=", mean_minutes, " minutes\n", sep = "")
stopifnot(identical(minutes, c(10, 20, 30)))
count=3; mean=20 minutes
Assignment creates named objects, mean returns a new result, and the assertion checks that the supplied vector is unchanged. Expected output is derived, not executed.
The workspace can hide an accidental dependency
An object created yesterday may still exist in an interactive session, masking a missing input in the script. Search paths and attached packages can also change which function a name resolves to. For a reviewed program, define the inputs explicitly and use qualified names when a package boundary matters. Avoid automatically restoring an old workspace as part of a reproducibility claim. Record the language and package versions actually used for execution. This course requires only base and recommended R facilities, uses synthetic values, and does not install packages, connect to services, or load external datasets.
Functions create a clearer calculation boundary
The second fixture packages a duration summary into a function with one argument. Validation checks numeric input, nonempty length, and finite values before computing. The return value is a named vector, so callers can extract count and mean by name. Keeping the input explicit makes the calculation easier to reuse and test than reading a global variable called current_data. The validation is intentionally narrow: it does not prove that the numbers really represent minutes or that the observations were collected appropriately. Units and provenance remain part of the documented caller contract.
summarize_minutes <- function(values) {
stopifnot(is.numeric(values), length(values) > 0L, all(is.finite(values)))
c(count = length(values), mean = mean(values))
}
result <- summarize_minutes(c(4, 8, 12))
cat("count=", result[["count"]], "; mean=", result[["mean"]], "\n", sep = "")
cat("function=", is.function(summarize_minutes), "\n", sep = "")
count=3; mean=8
function=TRUE
The result depends on explicit arguments; named extraction avoids relying on the display layout of a named vector. R execution was not performed.
Separate expected behavior from performed verification
Every R example in this course has an explicitly derived expected result and uses only supplied synthetic data. The review environment has no R or Rscript executable, so the displayed programs are marked illustrative and non-runnable in the course renderer. No R parsing or runtime execution is claimed. A learner with a compatible base-R installation can save an example as a script and run it in a fresh session, then compare the output and assertions. Preserve the exact input, environment, and any warning if behavior differs. This distinction keeps teaching expectations separate from execution evidence.
Common errors and fixes
A script works only in the author’s console
- Why it happens
- An undeclared object or attached package remains in the workspace.
- How to fix it
- Define inputs and dependencies explicitly and rerun in a fresh session.
- Prevent it next time
- Keep a self-contained synthetic script as the review artifact.
A result appears in the console but not the script output
- Why it happens
- Automatic interactive printing was assumed to be an output contract.
- How to fix it
- Use explicit print or cat at the intended boundary.
- Prevent it next time
- Check exact displayed output independently of interactive history.
A summary is interpreted in the wrong unit
- Why it happens
- The numeric vector did not carry an enforced measurement contract.
- How to fix it
- Document units and validate domain-specific ranges where justified.
- Prevent it next time
- Use meaningful names and preserve provenance beside the values.
Check your understanding
1. Why is a function argument preferable to reading a global vector for a reusable summary?
Show worked solution
The caller can see and control the input, two datasets can be processed without rebinding a global name, and a test can supply a small known vector. A function can still depend on enclosing state, so review its body and free names rather than assuming that a function declaration alone guarantees independence.
2. For durations 6, 12, and 18, what should the first fixture’s count and mean become?
Show worked solution
The count remains three and the mean is twelve minutes because the total is thirty-six divided by three. Replace only the supplied vector and preserve the unit label. An unexpected result should prompt inspection of the actual vector and any overwritten mean function before changing the arithmetic.
Key takeaways
- A script should declare the state it requires.
- Objects carry type and shape as well as values.
- Derived expected outputs are distinct from runtime verification.