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
- Start with Points (0, 1) and (1, 3)
- Do this Predict at x = 2
- Result 5
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.
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 = "")
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
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.
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.