توضیح 1
The live starter code is self-contained and uses only runner-compatible functions.
Loading
درس 4 از 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.
توضیح 1
The live starter code is self-contained and uses only runner-compatible functions.
توضیح 2
Book-only outputs are labelled when the separate source dataset or advanced package was not supplied.
توضیح 3
R code, paths, function names, and formulas remain left-to-right in every locale.
اصطلاحات
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)
نمادگذاری و فرمولها
future value = principal × (1 + annual rate)^years
Keep full precision in the object and round only for display.
مثال حلشده
سناریو
What is $1,000 worth after ten years at 5% annual compounding?
بررسی با R
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
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.
تمرین هدایتشده
سناریو
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.
توضیح 1
Write a numeric percent converter.
توضیح 2
Rewrite a nested calculation with |>.
توضیح 3
Record sessionInfo() without setwd().
Selected solutions
These are compact solution routes. Confirm dimensions, units, and any changed modelling choices.
توضیح 1
to_percent <- function(x) { stopifnot(is.numeric(x)); 100*x }
توضیح 2
x |> mean() |> round(2)
توضیح 3
capture.output(sessionInfo(), file=file.path('outputs','session_info.txt'))
Chapter summary
Turn repeated calculations into validated functions and portable, reproducible workflows.
توضیح 1
Functions expose reusable rules.
توضیح 2
Pipes clarify linear transformations.
توضیح 3
Pure calculations are easiest to test.
توضیح 4
Seeds and relative paths support reproducibility.
اصطلاحات
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.
منبع
The authoritative 125-page English PDF accompanies this native lesson.
دریافتبازاندیشی
Name the assumption, evidence you would seek, and how the recommendation might change.
ارزیابی پایانی