Explanation 1
The live starter code is self-contained and uses only runner-compatible functions.
Loading
Lesson 4 of 22
Turn repeated calculations into validated functions and portable, reproducible workflows.
Motivation
Small functions with clear contracts turn one successful calculation into a process another analyst can test and safely modify.
Why this matters
Turn repeated calculations into validated functions and portable, reproducible workflows.
Packages and data
Base R 4.1 or newer for the native |> pipe.
Explanation 1
The live starter code is self-contained and uses only runner-compatible functions.
Explanation 2
Book-only outputs are labelled when the separate source dataset or advanced package was not supplied.
Explanation 3
R code, paths, function names, and formulas remain left-to-right in every locale.
Terminology
Arguments state inputs; validation enforces assumptions; return value states output.
compound_value(principal, rate, years)
Depends only on inputs and does not alter external state.
mean-centering a supplied vector
Relative paths, fixed seeds, and session metadata explain how results were made.
set.seed(404)
Notation and formulas
future value = principal × (1 + annual rate)^years
Keep full precision in the object and round only for display.
Worked example
Scenario
What is $1,000 worth after ten years at 5% annual compounding?
R check
compound_value <- function(principal, annual_rate, years) {
stopifnot(principal >= 0, annual_rate > -1, years >= 0)
principal * (1 + annual_rate)^years
}
print(compound_value(1000, 0.05, 10))
set.seed(404)
print(mean(rnorm(1000)))The function exposes the compounding model and rejects impossible inputs; the seed reproduces this pseudorandom stream. Limitation: A fixed seed does not make one simulation representative, and a constant 5% rate is a modelling assumption.
Visual
Future value rises over longer horizons under a constant positive rate.
R connection
Run the self-contained starter code in the protected STATLAB R runner. The code prints an auditable result and avoids network or unrestricted file access.
Live R Lab
Run a self-contained example, verify its output, and explain one limitation for functions, pipes, and project workflow.
Ready to run
Common mistake
Do not install packages or change the working directory inside an analysis script.
STATLAB Tip
Give each function one job and test ordinary, boundary, and invalid inputs.
Guided practice
Scenario
Write annualize_volatility(x, periods = 12), validate periods, and explain the result for constant x.
Compare your result with the definition, units, and model assumptions—not only with a target number.
Exercises
Complete these without looking at the selected solutions. More than one defensible program may exist.
Explanation 1
Write a numeric percent converter.
Explanation 2
Rewrite a nested calculation with |>.
Explanation 3
Record sessionInfo() without setwd().
Selected solutions
These are compact solution routes. Confirm dimensions, units, and any changed modelling choices.
Explanation 1
to_percent <- function(x) { stopifnot(is.numeric(x)); 100*x }
Explanation 2
x |> mean() |> round(2)
Explanation 3
capture.output(sessionInfo(), file=file.path('outputs','session_info.txt'))
Chapter summary
Turn repeated calculations into validated functions and portable, reproducible workflows.
Explanation 1
Functions expose reusable rules.
Explanation 2
Pipes clarify linear transformations.
Explanation 3
Pure calculations are easiest to test.
Explanation 4
Seeds and relative paths support reproducibility.
Terminology
define a rule
Use in Functions, Pipes, and Project Workflow.
assert conditions
Use in Functions, Pipes, and Project Workflow.
native pipe
Use in Functions, Pipes, and Project Workflow.
reproduce draws
Use in Functions, Pipes, and Project Workflow.
References and provenance
Safavi (2026), Chapter 4. Student notes: Mohammad Safavi, Ph.D., STATLAB Academy, Version 1.0.
Resource
The authoritative 125-page English PDF accompanies this native lesson.
DownloadReflection
Name the assumption, evidence you would seek, and how the recommendation might change.
Exit check
Reach 70% to complete the chapter. Explanations appear after submission.
Checkpoint
Question 1 of 2. Answered 0/2. Passing score: 70%.