Prepare a short, reproducible report on a calibration dataset. Your central question is:
Which observations deserve closer inspection, and how does that judgement change when we consider an explanatory variable?
Work in groups of 2–4. Before computing each new analysis, discuss what you expect to learn. Then compare your prediction with the evidence. Keep a short record of conclusions that change as your analysis progresses.
Complete the code chunks and replace the response prompts with your own explanations. The import chunk is ready to run; the analysis chunks contain comments only, so the initial document can be knitted before you complete it. Use either base R graphics or ggplot2, and keep your plotting conventions consistent. Base R is sufficient for every required analysis.
Suggested working time: 90 minutes, followed by a short group discussion.
Imagine a laboratory evaluating a sensor. In each calibration run, a
reference input is set to a known level, x, and the sensor
produces a reading, y. The aim is to understand how the
readings vary with the input and to identify runs that require further
investigation.
This is a simulated teaching dataset, framed as a fictional calibration study. It is not a collection of real laboratory measurements or a random sample intended to represent a wider population. The construction details will be discussed after your initial analysis.
Each row represents one run. Row order does not represent time. Three runs, labelled A, B and C, will be followed throughout the activity; these labels do not indicate that a measurement is wrong.
| Variable | Meaning | Type / units |
|---|---|---|
id |
Unique identifier for the calibration run | Character identifier |
x |
Reference input level | Numeric, arbitrary input units |
y |
Sensor reading | Numeric, arbitrary response units |
Save this Rmd in your working folder and place
boxplots_data.csv in its data subfolder. Keep
that relative path when you knit your report. The CSV uses commas to
separate fields and a decimal point for numeric values.
data_path <- file.path("data", "boxplots_data.csv")
if (!file.exists(data_path)) {
stop("Place boxplots_data.csv in the data folder next to this Rmd.")
}
dat_raw <- read.csv(data_path, stringsAsFactors = FALSE)
dat <- dat_raw
case_ids <- c("A", "B", "C")
head(dat)
str(dat)
#> 'data.frame': 83 obs. of 3 variables:
#> $ id: chr "R01" "R02" "R03" "R04" ...
#> $ x : num 0 0.127 0.253 0.38 0.506 ...
#> $ y : num 8.8 11.2 10 13.6 12.8 ...
Keep dat_raw unchanged. Add derived variables to
dat and create a separate copy for the later hypothetical
modification. Select observations using id, not their row
numbers.
If needed, install knitr and rmarkdown once
from the R console. RStudio’s Knit button renders the
document; Pandoc is bundled with RStudio. If you choose ggplot2, install
it and load it in your setup chunk.
Useful functions include nrow(), names(),
summary(), is.na(), is.finite()
and anyDuplicated().
# Add your data checks here.
Your response: report any data-quality issues and list your planned analyses. At this stage, do not discard observations because they look unusual.
For this step, base your interpretation on y alone. Save
your conclusions before plotting the relationship with
x.
y.y and overlay all observations. Label
A, B and C so that they remain distinguishable. Jitter only the
categorical plotting position.dat$marginal_flag.For base R, use the box edges returned by
boxplot.stats() to match the convention used by
boxplot(). Its stats vector contains the lower
whisker, lower box edge, median, upper box edge and upper whisker, in
that order. If you use ggplot2, state which quartile convention you use
for classification.
The fences are
\[ L=Q_1-1.5(Q_3-Q_1), \qquad U=Q_3+1.5(Q_3-Q_1). \]
# Calculate descriptive summaries and fences.
# Create dat$marginal_flag and list flagged IDs.
# Draw the boxplot with observations and labels.
Your response: which of A, B and C are flagged? Explain what this rule establishes and what further information would be needed before calling a reading a measurement error. Distinguish a fence from a whisker endpoint.
Record your initial judgement. Write one sentence about each of A, B and C using only the evidence from this step. Keep these sentences for comparison with your later conclusions.
y against x and label A, B and
C.y ~ x using
all observations. Name the fitted model
fit and report its intercept and slope.dat$fitted and dat$residual.Useful functions include lm(), coef(),
fitted(), resid(), abline(),
segments() and text().
# Fit the model to every observation.
# Add fitted values and residuals to dat.
# Plot the data, fitted line and labelled residual segments.
Your response: revisit your three initial sentences.
Which judgements change after considering x? Identify any
observation whose predictor value extends beyond the range covered by
most other runs. What assumption is needed to interpret the fitted line
there?
The generating relationship is not supplied at this stage. Base your report on the observed data and fitted model, and distinguish an estimated relationship from a known scientific law.
For observation \(i\), the residual is
\[ e_i=y_i-\widehat y_i, \qquad \widehat y_i=\widehat\beta_0+\widehat\beta_1x_i. \]
dat$residual_flag.x. Add a horizontal reference at
zero and label A, B and C. You may also draw the residual boxplot
fences.id,
x, y, fitted value, residual, marginal flag
and residual flag.# Calculate residual fences and dat$residual_flag.
# Create both residual plots and the comparison table.
Your response: explain the difference between being unusual among all responses and being unusual relative to the fitted relationship. Does a residual boxplot reveal everything visible in the residual-versus-predictor plot? Discuss any pattern in the centre or spread of the residuals.
Residuals are calculated after fitting the model and are not independent copies of its errors. Under the usual constant-variance linear model, their variances depend on leverage. Treat this flagging rule as an exploratory diagnostic, not a formal test with a universal significance level.
These quantities answer different questions:
| Quantity | Question | Useful R functions |
|---|---|---|
| Residual size | How far is the response from the fitted line? | resid(), rstandard(),
rstudent() |
| Leverage | How unusual is the predictor value relative to the others? | hatvalues() |
| Influence | How much does the fitted relationship depend on this observation? | cooks.distance(), refitting after
omission |
With an intercept and one predictor,
\[ h_{ii}=\frac{1}{n}+\frac{(x_i-\bar x)^2}{\sum_j(x_j-\bar x)^2}. \]
Cook’s distance combines residual size and leverage. Standardized residuals adjust for leverage and use the overall estimated error scale. Externally studentized residuals estimate that scale with the observation omitted.
# Calculate the diagnostic quantities.
# Build a labelled table and compare the rankings.
Your response: can a high-leverage observation have a small residual? Must the largest response be the most influential observation? Support your answers with your results. Explain why the diagnostic table does not by itself justify deleting observations.
Use predict(..., newdata = dat) to evaluate each reduced
model at the same locations. Do not compare fitted-value vectors of
different lengths.
# Refit after omitting each labelled case separately.
# Compare coefficients and predictions at the original x values.
Your response: which omissions change the slope or predictions most? Compare this evidence with Cook’s distance. Does any comparison require a reduced model to predict outside its remaining predictor range? This is a sensitivity analysis; it is not a new cleaned dataset.
Create a copy named dat_shift. Increase A’s response by
25 units, keeping its predictor and every other
observation unchanged. Keep the original dat.
Before computing: predict whether A’s leverage, its residual, its Cook’s distance and the fitted slope will change. Give a reason for each prediction.
fit_shift.# Copy the data, then modify A's y value only.
# Refit: previously stored fitted values and residuals are now outdated.
# Recalculate diagnostics from the modified model.
# Create the comparison table and the two scatterplots.
Your response: compare the results with your predictions. Explain how an observation can affect the line against which its own residual is measured. Why can ranking observations only by raw residual size be insufficient?
Submit the completed Rmd and its knitted HTML. Your report should contain:
Figures may be combined into panels. Every figure needs informative axis labels and a caption explaining its analytical purpose. Every important claim should point to a plot, a table or a calculation.
During the group discussion, compare:
x;If you use AI assistance, keep the prompt and describe how you checked the returned code and interpretations. You remain responsible for the analysis.
Note on AI assistance
These teaching materials were prepared with assistance from ChatGPT (OpenAI) in drafting explanations, developing examples and generating R code. The author retains responsibility for the final content.