The Analogy: Calibrating a Spring Balance with Test Weights
A spring balance is a hook, a spring, and a pointer that moves along a printed scale. Before anyone can trust the number the pointer shows, the balance has to be calibrated, and the way to calibrate it is to hang weights whose true mass is already certified -- a set of test weights -- and write down what the pointer reads for each. If the balance were perfect, the reading would equal the true weight every time; in practice each reading sits a little off, and the calibration is the job of working out how the readings relate to the truth.
That relationship, for a balance in good order, is a straight line: the reading equals a fixed offset plus a gain times the true weight. Fitting the line means drawing the single straight line through the scatter of test points that sits closest to all of them, in the sense of making the squared vertical gaps as small as possible. The slope of that line estimates the gain -- how many units the pointer moves per unit of real weight -- and the intercept estimates the offset -- what the pointer reads with nothing on the hook. The gaps left over, the residuals, measure how repeatable the balance is.
Two numbers come out of the fit and they answer different questions. The intercept asks whether the balance has a zero error: does the pointer sit off zero when the hook is empty. The slope asks whether it has a gain error: does it read proportionally high or low as the load grows. A balance can be flawless on one and badly wrong on the other -- dead-on at zero but reading five percent heavy at every weight, or accurate in proportion but stuck two grams high across the whole scale.
The trap is to ask the fit the wrong question. The obvious test a statistics tool hands you is whether there is any relationship between reading and weight at all -- whether the slope differs from zero -- and of course there is; any balance that responds to weight passes that test overwhelmingly. But that was never the calibration question. Calibration asks whether the gain is exactly one and the offset exactly zero, and a balance reading five percent heavy has a slope significantly different from one while sailing through the slope-differs-from-zero test with a tiny p-value. Reading that tiny p-value as proof of calibration certifies a biased instrument. And the fitted line is only evidence across the range of test weights actually hung; trusting it to predict the reading for a load far heavier than any test weight is trusting the spring to stay straight where it was never checked.
Syntax or Core Structure
The lm() function fits a linear model by ordinary least squares. You give it a formula, response ~ predictor, and a data frame, and it returns a model object carrying the coefficients, the residuals, and everything needed to test and predict. Here a balance is checked against five certified weights.
cal <- data.frame(
weight = c(10, 20, 30, 40, 50), # certified test weights
reading = c(14, 19, 34, 39, 54) # what the balance showed
)
fit <- lm(reading ~ weight, data = cal)
co <- coef(fit)
sm <- summary(fit)
writeLines(sprintf("%-14s: %d", "n", nrow(cal)))
writeLines(sprintf("%-14s: %.2f", "intercept", unname(co["(Intercept)"])))
writeLines(sprintf("%-14s: %.2f", "slope", unname(co["weight"])))
writeLines(sprintf("%-14s: %.4f", "r.squared", sm$r.squared))
writeLines(sprintf("%-14s: %.4f", "slope t", sm$coefficients["weight", "t value"]))
writeLines(sprintf("%-14s: %.4f", "slope p", sm$coefficients["weight", "Pr(>|t|)"]))
writeLines(sprintf("%-14s: %d", "df resid", as.integer(sm$df[2])))
Output:
n : 5
intercept : 2.00
slope : 1.00
r.squared : 0.9709
slope t : 10.0000
slope p : 0.0021
df resid : 3
The fit reports a slope of 1.00 and an intercept of 2.00: this balance's gain is spot on -- one unit of pointer per unit of true weight -- but it carries a two-unit zero offset. The r-squared of 0.9709 says the straight line explains 97 percent of the variation in the readings, so the points sit tightly around it. The slope's t statistic of 10.0 measures how many standard errors the slope sits from zero, and its p-value of 0.0021 easily rejects the null that the slope is zero. That is the balance responding to weight at all -- important, but not yet the calibration verdict, which is a separate question this default test does not answer.
Technical Depth: Coefficients, Fit, and Prediction
The coefficient table
The heart of summary(fit) is the coefficient table, and each row tests one coefficient against zero. It has four columns, and reading them in order tells you the whole story of one coefficient:
| Column | What it reports | How to read it |
|---|---|---|
| Estimate | The fitted coefficient value | The size and direction of the effect |
| Std. Error | The uncertainty in that estimate | Smaller means a more precise estimate |
| t value | The estimate divided by its standard error | Larger magnitude is stronger evidence |
| p-value | The two-sided tail on the residual df | Below your alpha rejects the zero null |
The printed column for the p-value is headed with the probability of a t at least as extreme in absolute value, but you never have to parse that header: you reach every cell by name from sm$coefficients, a plain numeric matrix, rather than reading the formatted block.
sm <- summary(fit)
cf <- sm$coefficients
writeLines(sprintf("%-11s%10s%9s%9s%9s", "TERM", "ESTIMATE", "STDERR", "T", "P"))
writeLines(strrep("-", 48))
for (term in rownames(cf)) {
writeLines(sprintf("%-11s%10.3f%9.3f%9.3f%9.4f",
term, cf[term, "Estimate"], cf[term, "Std. Error"],
cf[term, "t value"], cf[term, "Pr(>|t|)"]))
}
writeLines(strrep("-", 48))
writeLines(sprintf("%-20s: %.4f", "residual std error", sm$sigma))
writeLines(sprintf("%-20s: %d", "residual df", as.integer(sm$df[2])))
Output:
TERM ESTIMATE STDERR T P
------------------------------------------------
(Intercept) 2.000 3.317 0.603 0.5890
weight 1.000 0.100 10.000 0.0021
------------------------------------------------
residual std error : 3.1623
residual df : 3
Read the two rows against the calibration questions. The intercept is 2.000 but its standard error is 3.317, so its t is only 0.603 and its p-value 0.5890: the two-unit offset is not distinguishable from zero at this sample size, so on this evidence the balance has no proven zero error. The weight row is the slope, estimate 1.000 with a standard error of 0.100, giving a t of 10.0 and p of 0.0021 -- the slope is firmly different from zero. The residual standard error of 3.1623 is the typical size of a reading's miss from the line, and the three residual degrees of freedom are the five points minus the two coefficients the fit spent.
Overall fit: R-squared and the F-test
Beyond the individual coefficients, the model has an overall goodness of fit. R-squared is the fraction of the response's variance the model explains; adjusted R-squared penalises it for the number of predictors. The F-statistic tests whether the model as a whole beats an intercept-only model, and in simple regression it is exactly the slope's t squared.
sm <- summary(fit)
Fval <- unname(sm$fstatistic["value"])
d1 <- unname(sm$fstatistic["numdf"])
d2 <- unname(sm$fstatistic["dendf"])
model_p <- pf(Fval, d1, d2, lower.tail = FALSE)
slope_t <- sm$coefficients["weight", "t value"]
writeLines(sprintf("%-16s: %.4f", "r.squared", sm$r.squared))
writeLines(sprintf("%-16s: %.4f", "adj.r.squared", sm$adj.r.squared))
writeLines(sprintf("%-16s: %.3f", "F statistic", Fval))
writeLines(sprintf("%-16s: %d %d", "F df", as.integer(d1), as.integer(d2)))
writeLines(sprintf("%-16s: %.4f", "model p", model_p))
writeLines(sprintf("%-16s: %s", "F is slope t^2",
if (abs(Fval - slope_t^2) < 1e-6) "TRUE" else "FALSE"))
writeLines(sprintf("%-16s: %s", "model p is slope p",
if (abs(model_p - sm$coefficients["weight", "Pr(>|t|)"]) < 1e-10) "TRUE" else "FALSE"))
Output:
r.squared : 0.9709
adj.r.squared : 0.9612
F statistic : 100.000
F df : 1 3
model p : 0.0021
F is slope t^2 : TRUE
model p is slope p: TRUE
The F-statistic is 100.0, which is exactly the slope's t of 10.0 squared, and its p-value equals the slope's p-value to the last digit -- in a one-predictor model the F-test and the slope's t-test ask the identical question, so they must agree. That equality is a useful self-check. The warning that rides with R-squared is the important lesson: 0.9709 says the points hug the line tightly, but it says nothing about whether the line is the right line. A balance reading five percent heavy can produce an r-squared of 0.999, because the readings still fall on a beautifully straight line -- just the wrong one. High R-squared means precise, not accurate.
Fitted values, residuals, and the danger of extrapolation
The model predicts with predict(), and every fitted value plus its residual reconstructs the original reading exactly. Prediction inside the range of the test weights is interpolation, which the data supports; prediction far outside it is extrapolation, which it does not.
newdata <- data.frame(weight = c(35, 100))
preds <- predict(fit, newdata = newdata)
writeLines(sprintf("%-16s: %s", "weights", paste(cal$weight, collapse = " ")))
writeLines(sprintf("%-16s: %s", "fitted",
paste(sprintf("%d", round(fitted(fit))), collapse = " ")))
writeLines(sprintf("%-16s: %s", "residuals",
paste(sprintf("%d", round(residuals(fit))), collapse = " ")))
writeLines(sprintf("%-16s: %s", "range of x",
paste(range(cal$weight), collapse = " ")))
writeLines(sprintf("%-16s: %.1f", "predict at 35", unname(preds[1])))
writeLines(sprintf("%-16s: %.1f", "predict at 100", unname(preds[2])))
writeLines(sprintf("%-16s: %s", "extrapolated",
if (100 > max(cal$weight)) "TRUE" else "FALSE"))
Output:
weights : 10 20 30 40 50
fitted : 12 22 32 42 52
residuals : 2 -3 2 -3 2
range of x : 10 50
predict at 35 : 37.0
predict at 100 : 102.0
extrapolated : TRUE
The fitted values are the line's predictions at the test weights, and adding back the residuals 2, -3, 2, -3, 2 recovers the original readings exactly -- that is what least squares guarantees. The prediction at 35 is a genuine interpolation: 35 sits inside the tested range of 10 to 50, so the line has evidence there and 37.0 is trustworthy. The prediction at 100 is flagged as extrapolated because 100 is double the heaviest test weight. The number 102.0 comes out cleanly, but it rests entirely on the spring staying perfectly linear across a range it was never tested over, and a real spring may sag or bind under a load that heavy. R will not warn you; the flag has to be your own.
Real World Example: Auditing a Weighbridge That Reads High
A depot's weighbridge is suspected of reading heavy, costing the depot money on every outbound load it over-declares. The metrologist drives six certified reference weights across it and records what the bridge reports. The naive audit fits a line and checks whether the reading depends on the true weight -- but that is the wrong question. A biased bridge still produces a near-perfect straight line; the audit that matters is whether the slope differs from one, because a correctly calibrated bridge has slope exactly one. This program fits the line, then runs both tests side by side so the difference is unmistakable.
audit <- data.frame(
weight = c(10, 20, 30, 40, 50, 60),
reading = c(13, 23, 34, 44, 55, 65)
)
fit <- lm(reading ~ weight, data = audit)
co <- coef(fit)
se <- summary(fit)$coefficients[, "Std. Error"]
dfr <- fit$df.residual
# default test: is the slope different from zero?
t_vs0 <- co[["weight"]] / se[["weight"]]
p_vs0 <- 2 * pt(-abs(t_vs0), dfr)
# calibration test: is the slope different from ONE?
t_vs1 <- (co[["weight"]] - 1) / se[["weight"]]
p_vs1 <- 2 * pt(-abs(t_vs1), dfr)
alpha <- 0.05
writeLines(sprintf("%-8s%9s%9s", "WEIGHT", "READING", "FITTED"))
writeLines(strrep("-", 26))
for (i in seq_len(nrow(audit))) {
writeLines(sprintf("%-8d%9d%9.2f",
audit$weight[i], audit$reading[i], fitted(fit)[i]))
}
writeLines(strrep("-", 26))
writeLines("")
writeLines(sprintf("%-20s: %.4f", "slope", co[["weight"]]))
writeLines(sprintf("%-20s: %.4f", "intercept", co[["(Intercept)"]]))
writeLines(sprintf("%-20s: %.4f", "r.squared", summary(fit)$r.squared))
writeLines(sprintf("%-20s: %.3f", "t slope vs 0", t_vs0))
writeLines(sprintf("%-20s: %.4f", "p slope vs 0", p_vs0))
writeLines(sprintf("%-20s: %.3f", "t slope vs 1", t_vs1))
writeLines(sprintf("%-20s: %.4f", "p slope vs 1", p_vs1))
writeLines(sprintf("%-20s: %s", "passes vs 0", if (p_vs0 < alpha) "YES" else "no"))
writeLines(sprintf("%-20s: %s", "off vs 1", if (p_vs1 < alpha) "YES" else "no"))
Output:
WEIGHT READING FITTED
--------------------------
10 13 12.86
20 23 23.31
30 34 33.77
40 44 44.23
50 55 54.69
60 65 65.14
--------------------------
slope : 1.0457
intercept : 2.4000
r.squared : 0.9998
t slope vs 0 : 149.419
p slope vs 0 : 0.0000
t slope vs 1 : 6.532
p slope vs 1 : 0.0028
passes vs 0 : YES
off vs 1 : YES
The r-squared is 0.9998, so by the usual reflex the model is a triumph -- the readings sit almost exactly on the fitted line. The default test agrees emphatically: the slope's t against zero is 149.4, its p-value rounds to 0.0000, and the audit "passes." That is the trap. Passing the slope-versus-zero test only confirms the bridge responds to weight, which no one doubted. The number that matters is the slope itself, 1.0457: the bridge reads about four and a half percent heavy across the board.
The calibration test makes the fault visible. Testing the slope against one gives a t of 6.532 on four degrees of freedom and a p-value of 0.0028, comfortably below 0.05, so the slope is significantly different from one. The bridge is biased, and the audit that asked the right question caught it while the audit that asked the reflexive question waved it through. The two tests use the same estimate and the same standard error; only the null differs, and only one null is the one the depot cares about.
This program has real limits, and the sharpest one is baked into how regression is usually taught and used. The most dangerous flaw is that the default summary(lm()) output reports only the slope-versus-zero test, so an analyst who reads the printed p-value and stops -- exactly what most people do -- concludes the bridge is fine when it is skimming money on every load. The extra test against one is not something R volunteers; you have to know to write it. Beyond that, the intercept of 2.4 units is a second, separate error the slope test ignores entirely -- even a bridge with slope one would be wrong by 2.4 on a light load, and this analysis never tests the intercept against zero. And the whole audit spans 10 to 60 units; the depot routinely ships loads far heavier, where the bridge's behaviour is untested and the tidy 0.9998 fit is no guarantee at all.
Common Mistakes
- Reading a high R-squared as proof the model is correct. R-squared measures how tightly the points hug the fitted line, not whether the line is the right one. A systematically biased instrument produces a near-perfect R-squared because its errors are proportional, not scattered. High R-squared means precise; it says nothing about accurate.
- Trusting the default slope-versus-zero test when your real null is a different value.
summary(lm())tests every coefficient against zero. When calibration asks whether a slope equals one, or a difference equals a target, you must build that test yourself from the estimate and its standard error. The printed p-value answers a question you were not asking.
- Extrapolating beyond the range of the fitted data. The model has evidence only between the smallest and largest observed predictor values.
predict()will happily return a number for any input, including inputs far outside that range, but those predictions rest on the untestable assumption that the relationship stays linear where you never measured it.
- Confusing the intercept's significance with its importance. A large p-value on the intercept means the data cannot distinguish it from zero, not that it is zero. With few points and predictors far from the origin, the intercept's standard error is large, so even a real offset can look insignificant. Absence of evidence is not evidence of absence.
- Fitting a line to a relationship that is not linear.
lm()fits the best straight line through any cloud of points, even a clearly curved one. Always inspect residuals against fitted values: a pattern there -- a smile, a frown, a funnel -- means the linear form is wrong and the coefficients, standard errors, and p-values are all misleading.
- Swapping the response and the predictor.
lm(y ~ x)andlm(x ~ y)are different models with different slopes; regression is not symmetric. The response goes on the left of the tilde and is the quantity whose variation you are explaining. Getting this backwards inverts the whole interpretation.
- Ignoring influential points. A single outlier with an extreme predictor value can swing the slope by itself, because least squares minimises squared errors and one distant point contributes an enormous square. Check for high-leverage points before trusting a slope; one bad reading can dominate five good ones.
- Treating the standard errors as valid when residuals are correlated or heteroscedastic. The usual standard errors assume the residuals are independent and share a constant variance. Time-ordered data often violates independence, and many processes have errors that grow with the fitted value. When those assumptions fail, the coefficients may still be reasonable but the p-values and confidence intervals are not.
- Rounding coefficients before using them for prediction. Reading "slope 1.05, intercept 2.40" off the printout and computing predictions by hand introduces error that compounds across the range. Always predict from the fitted model object with
predict(), which carries full precision, rather than from the rounded numbers you displayed.
Best Practices
- Plot the data before fitting and plot the residuals after. The scatter tells you whether a line is even the right shape, and the residual plot tells you whether the fit you got honoured the assumptions behind its p-values.
- State your null hypothesis explicitly before reading any p-value, and if it is not "the coefficient is zero," construct the test you actually need from the estimate and its standard error rather than accepting the default.
- Extract results by name from
coef(fit)andsummary(fit)$coefficientsrather than by position or by eye. Named access survives a change in the order of predictors and documents which number you meant.
- Record the range of each predictor alongside the model, and refuse to report predictions outside it without flagging them as extrapolation. Make the flag part of the output, not a note you rely on remembering.
- Report the estimate with its standard error or confidence interval, never the point estimate alone. A slope of 1.05 with a standard error of 0.30 tells a completely different story from 1.05 with a standard error of 0.01.
- Check R-squared and residual standard error together. R-squared is scale-free and easy to inflate; the residual standard error is in the units of the response and tells you the typical size of a miss in terms you can act on.
- Keep the fitted model object and predict from it, rather than transcribing coefficients into a separate calculation. The object carries full precision and the exact model structure, so predictions and diagnostics stay consistent.
- Validate a calibration on data the fit has never seen, not on the points that produced it. A model always fits its own training points well; the honest test of a calibration line is how it does on the next reading.
Practice Exercises
- Fit
lm(y ~ x)tox = c(1, 2, 3, 4, 5)andy = c(2, 4, 5, 4, 5), then extract the slope and intercept by name fromcoef(). Compute the fitted values by hand from those two numbers and confirm they matchfitted()to full precision.
- Using any fitted model, write the calibration test that checks whether the slope differs from one instead of from zero. Compute the t statistic as the estimate minus one over its standard error, get the two-sided p-value with
pt(), and compare it to the slope-versus-zero p-value thatsummary()prints.
- Take a model fitted on predictor values spanning 10 to 50 and use
predict()to forecast at 30 and at 200. Write code that compares each new predictor value torange()of the training data and prints INTERPOLATION or EXTRAPOLATION for each, so the risky prediction is labelled automatically.
- Confirm the identity between the F-test and the slope's t-test in simple regression. Fit any one-predictor model, pull the F-statistic from
summary(fit)$fstatistic, square the slope's t value, and show the two are equal; then show their p-values match by computing both from the appropriate distributions.