Library contents

R stats::lm and predict

lm fits a linear model from a formula and a data frame. predict uses the fitted coefficients to estimate the response for new predictor values.

A simple example

stats::lm and predict

  1. Start with Points (0, 1) and (1, 3)
  2. Do this Predict at x = 2
  3. Result 5
The fitted line rises by two per step and starts at one.

Syntax

R syntax
fit <- lm(cost ~ units, data = history)
Run this example in R

Save the program as Lesson.R. Use R 4.x.

Rscript --vanilla Lesson.R

Predict a value from a fitted straight line

A manager has observations that follow an approximately straight-line relationship. Fit or use that relationship to estimate a new value and interpret it as a prediction from the sample.

From the programcat(paste(round(coef(fit), 1), collapse = " "), "\n", sep = "")
First output line2 3
Lesson.R
history <- data.frame(units = c(1, 2, 3, 4), cost = c(5, 8, 11, 14))
fit <- lm(cost ~ units, data = history)
cat(paste(round(coef(fit), 1), collapse = " "), "\n", sep = "")
estimate <- predict(fit, newdata = data.frame(units = 2.5))
cat(round(unname(estimate), 1), "\n", sep = "")
Output
2 3
9.5

The history follows a two-unit fixed charge plus three units of cost for each item. The estimate stays inside the observed predictor range. Real data can also carry residual variation and uncertainty.

R documentation for stats::lm and predict

Advertisements

Estimate a small print job

A print shop observes a fixed setup cost plus a constant price per sheet. Fit the straight line determined by the observed pairs, then predict the value at the requested input.

Given1→5 · 2→8 · 3→11 | predict 4
Worked result14

Estimate a delivery charge

The class models charges with a fixed booking fee and a constant amount per kilometre. Fit the straight line determined by the observed pairs, then predict the value at the requested input.

Given1→7 · 3→11 | predict 4
Worked result13