ZetCode

R linear regression

last modified November 19, 2026

Linear regression fits a straight line through a set of points and describes how one variable changes when another changes. The function lm estimates the line by least squares, and the resulting object carries the coefficients, the fitted values, the residuals, and the quantities needed for inference. A formula such as scores ~ hours reads as "scores modelled by hours", with the response on the left and the predictors on the right. This article covers a simple regression, the summary, fitted values and residuals, confidence and prediction intervals, multiple predictors, and a categorical predictor.

Fitting a line

lm returns an object that prints a short summary by default: the call that produced it and the estimated coefficients. The intercept is the predicted value when every predictor is zero, and each slope is the predicted change in the response for a one-unit increase in its predictor.

fit.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
fit <- lm(scores ~ hours)
cat("observations:", length(hours), "\n")
cat("residual sd:", summary(fit)$sigma, "\n")
print(fit)
print(coef(fit))

The model is fitted on eight observations, and its residual standard error is 1.83 points. The intercept is 49.91 and the slope is 3.674, so the model predicts about 3.67 more points for every additional hour of study. The intercept is the prediction at zero hours, which lies outside the observed range of two to twelve hours and should not be interpreted as a real exam result. The coefficients are estimates, not exact population values.

$ Rscript fit.R
observations: 8 
residual sd: 1.829954 

Call:
lm(formula = scores ~ hours)

Coefficients:
(Intercept)        hours  
     49.908        3.674  

(Intercept)       hours 
  49.907609    3.673913 

Reading the summary

summary adds the standard errors, the t statistics, the p-values, the residual standard error, and the coefficient of determination. The last one, labelled Multiple R-squared, is the fraction of the variation in the response that the model explains. The F statistic tests whether the model as a whole explains anything.

model-summary.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
fit <- lm(scores ~ hours)
print(summary(fit))

The slope has a standard error of 0.19 and a t statistic of 19.26, and its p-value of 1.3e-06 is far below 0.05. The residual standard error is 1.83 points, which is the typical distance between an observation and the line. R-squared is 0.984, so hours explain about ninety-eight percent of the variation in scores, and the F test agrees with the slope test because the model has only one predictor. Adjusted R-squared penalises extra predictors and is the fairer number when models are compared.

$ Rscript model-summary.R

Call:
lm(formula = scores ~ hours)

Residuals:
    Min      1Q  Median      3Q     Max 
-2.3207 -0.7880 -0.1359  1.3098  2.0489 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  49.9076     1.4840   33.63 4.60e-08 ***
hours         3.6739     0.1908   19.26 1.27e-06 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.83 on 6 degrees of freedom
Multiple R-squared:  0.9841,	Adjusted R-squared:  0.9814 
F-statistic: 370.8 on 1 and 6 DF,  p-value: 1.269e-06

Fitted values and residuals

fitted returns the prediction for every observation used to fit the model, and residuals returns the difference between the observed value and its fitted value. A residual is positive when the point lies above the line and negative when it lies below. predict applies the model to new data.

fitted-values.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
fit <- lm(scores ~ hours)
print(round(fitted(fit), 2))
print(round(residuals(fit), 2))
print(predict(fit, newdata = data.frame(hours = c(4, 10))))

The fitted values rise from 57.26 to 93.99, following the observed scores closely. The residuals range from -2.32 to 2.05 and sum to zero, which is a property of the least-squares fit. Predicting at four and ten hours gives 64.60 and 86.65 points. The second value is inside the observed range, while a prediction at twenty hours would extrapolate far beyond it.

$ Rscript fitted-values.R
    1     2     3     4     5     6     7     8 
57.26 60.93 68.28 71.95 79.30 82.97 90.32 93.99 
    1     2     3     4     5     6     7     8 
-2.26  1.07 -0.28  2.05 -0.30  2.03 -2.32  0.01 
       1        2 
64.60326 86.64674 

Confidence and prediction intervals

predict can return two kinds of interval. A confidence interval describes the average response at a given predictor value, while a prediction interval describes a single new observation. The prediction interval is always wider, because it adds the variability of the individual point to the uncertainty of the line.

intervals.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12)
scores <- c(55, 62, 68, 74, 79, 85, 88, 94)
fit <- lm(scores ~ hours)
new <- data.frame(hours = c(4, 10))
print(predict(fit, new, interval = "confidence"))
print(predict(fit, new, interval = "prediction"))
print(confint(fit))

At four hours the mean response is estimated between 62.49 and 66.72, while a new student at four hours is expected between 59.65 and 69.55. At ten hours the two intervals are 84.53 to 88.76 and 81.70 to 91.60. Both intervals widen toward the ends of the data, where the line is less certain. confint gives the interval for each coefficient: the slope lies between 3.21 and 4.14 points per hour.

$ Rscript intervals.R
       fit      lwr      upr
1 64.60326 62.48957 66.71695
2 86.64674 84.53305 88.76043
       fit      lwr      upr
1 64.60326 59.65171 69.55481
2 86.64674 81.69519 91.59829
                2.5 %    97.5 %
(Intercept) 46.276475 53.538743
hours        3.207077  4.140749

Multiple regression

A model with several predictors estimates the effect of each one while holding the others fixed. The formula lists the predictors with plus signs. The coefficient of a predictor is now its effect after the other predictors have been taken into account, which is why it can differ from the slope in a simple regression.

multiple.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12, 4, 7)
scores <- c(60, 54, 73, 67, 79, 85, 85, 93, 63, 75)
motivation <- c(6, 3, 8, 4, 7, 9, 5, 8, 6, 7)
fit <- lm(scores ~ hours + motivation)
print(summary(fit))

The data set has ten students, and both predictors are useful. The intercept is 39.81, hours adds 3.06 points per hour, and motivation adds 2.07 points per unit, with all three p-values below 0.001. The residual standard error falls to 1.27 points and R-squared rises to 0.992. The two predictors correlate at 0.42, so their effects are separable but not independent, and the coefficients should be read with that correlation in mind.

$ Rscript multiple.R

Call:
lm(formula = scores ~ hours + motivation)

Residuals:
     Min       1Q   Median       3Q      Max 
-1.50719 -0.97752  0.00227  0.97290  1.61908 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  39.8077     1.4954  26.620 2.70e-08 ***
hours         3.0631     0.1400  21.874 1.05e-07 ***
motivation    2.0745     0.2473   8.389 6.72e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.27 on 7 degrees of freedom
Multiple R-squared:  0.9919,	Adjusted R-squared:  0.9896 
F-statistic: 427.8 on 2 and 7 DF,  p-value: 4.812e-08

A categorical predictor

A factor in a formula is coded as a set of indicator variables. R uses the first level as the baseline, and the coefficients of the other levels measure their difference from that baseline. The built-in PlantGrowth data set contains the weight of thirty plants grown under a control condition and two treatments.

categorical.R
fit <- lm(weight ~ group, data = PlantGrowth)
print(fit)
print(summary(fit))

The intercept of 5.032 is the mean weight of the control group. Treatment one is 0.371 below the control, and treatment two is 0.494 above it, but only the second difference is close to significance at the ten percent level. The F test of the whole model gives a p-value of 0.016, so at least one group differs even though no single coefficient clears five percent. The individual tests and the overall test answer different questions, and the sample is small.

$ Rscript categorical.R

Call:
lm(formula = weight ~ group, data = PlantGrowth)

Coefficients:
(Intercept)    grouptrt1    grouptrt2  
      5.032       -0.371        0.494  


Call:
lm(formula = weight ~ group, data = PlantGrowth)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.0710 -0.4180 -0.0060  0.2627  1.3690 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   5.0320     0.1971  25.527   <2e-16 ***
grouptrt1    -0.3710     0.2788  -1.331   0.1944    
grouptrt2     0.4940     0.2788   1.772   0.0877 .  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.6234 on 27 degrees of freedom
Multiple R-squared:  0.2641,	Adjusted R-squared:  0.2096 
F-statistic: 4.846 on 2 and 27 DF,  p-value: 0.01591

A complete example

The final script fits the two-predictor model, reports the rounded coefficients, the explained variation, the residual spread, and a prediction for a new student. It also prints the range of the residuals, which is a quick check that no observation lies far from the fitted line.

report.R
hours <- c(2, 3, 5, 6, 8, 9, 11, 12, 4, 7)
scores <- c(60, 54, 73, 67, 79, 85, 85, 93, 63, 75)
motivation <- c(6, 3, 8, 4, 7, 9, 5, 8, 6, 7)
fit <- lm(scores ~ hours + motivation)
print(round(coef(fit), 2))
cat("r squared:", round(summary(fit)$r.squared, 3), "\n")
cat("residual sd:", round(summary(fit)$sigma, 2), "\n")
new <- data.frame(hours = 10, motivation = 7)
cat("predicted score:", round(predict(fit, new), 2), "\n")
print(range(residuals(fit)))

The model explains 99.2 percent of the variation in scores, and its residual standard deviation is 1.27 points. A student who studies ten hours with a motivation score of seven is predicted to score 84.96. The residuals run from -1.51 to 1.62, so every observation lies within about 1.6 points of its fitted value. A report should also include diagnostic plots and the number of observations, because a high R-squared on ten points is not the same evidence as a high R-squared on a thousand.

$ Rscript report.R
(Intercept)       hours  motivation 
      39.81        3.06        2.07 
r squared: 0.992 
residual sd: 1.27 
predicted score: 84.96 
[1] -1.507192  1.619076

Next steps

The correlation article covers the standardised version of the same relationship, and the hypothesis testing article explains the p-values attached to the coefficients. The base graphics article shows how to draw the scatter plot, and the logistic regression article replaces the normal model with one for a binary response.

Source

R documentation: lm

R documentation: summary.lm

R documentation: predict.lm

R documentation: confint

R documentation: the PlantGrowth data set

In this article we have fitted a simple regression with lm and read its coefficients, standard errors, R-squared, and F test. We computed fitted values and residuals, predicted new observations, and compared confidence intervals with prediction intervals. We added a second predictor, used a categorical predictor with a baseline level, and finished with a model report that included the residual spread. The series continues with R logistic regression.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.