Skip to main content
v2026.11,986 entries · CC-BY 4.0

lm in R: Fit a Linear Model and Read the Output

How lm() works in R: arguments, summary() output, extracting R-squared and the R value, abline plots and a hand-checked example.

Written and maintained by CASRAI Editorial Board

Published

On this page

lm() is R’s function for fitting a linear model by least squares: you give it a formula such as y ~ x and a data frame, and it returns a fitted object of class “lm” holding the coefficients, residuals and fitted values. You then call summary() on that object to read the coefficient table, the residual standard error and R-squared, and you pull individual numbers out of the summary with the dollar operator, for example summary(fit)$r.squared.

What lm() is used for in research

lm in R programming means the lm function in the stats package, documented in the R reference manual as the function used to fit linear models, and it covers simple regression, multiple regression and, with factor predictors, analysis of variance layouts (R documentation: lm). Researchers use it for four recurring jobs: estimating how an outcome changes with one or more predictors, adjusting a comparison for covariates, producing fitted values that feed a plot or a prediction, and checking residuals before trusting any of the above. The same fitted object supports all four, which is why the R introduction manual says you will almost always prefer lm() to the older lsfit() and stresses that the result is stored so you can interrogate it later with generic functions that react to its class (An Introduction to R).

This page is about the function itself: its arguments, where each printed number lives in the summary object, and how to extract the one you need for a table or a report. For generalised linear models and the wider modelling workflow see modeling in R. For predicted values on new data see prediction in R, and for the fitted-values side of the object see extracting fitted values in R.

Linear model in R and the lm function: the same thing

“Linear model in R”, “lm function in R” and “lm in R” all point to the same function. The word linear refers to the model being linear in its coefficients, not to the shape of the fitted curve, so a formula can contain transformed predictors and still be fitted by lm(). The documentation states that a formula has an implied intercept term, so y ~ x fits an intercept and a slope without you asking for the intercept (R documentation: lm).

How to install or access R and lm()

R itself is downloaded from CRAN, the Comprehensive R Archive Network. The Windows download page, for example, offers the current release as a base installer (CRAN: Download R for Windows), and CRAN publishes equivalent pages for the other operating systems from its main page. lm() is documented as part of the stats package, the package whose help index lists the modelling and statistical functions of base R (R documentation: The R Stats Package). It therefore needs no extra package installation: after installing R you can type ?lm at the console to open the same help page this guide cites.

To follow the examples you also need a data frame. The abline help page uses the cars data set that ships with R, with the stopping distance dist and the speed speed, and this guide uses the same call so that you can compare it with the official example (R documentation: abline).

How to fit a linear model with lm() step by step

  1. Put the variables in a data frame. One row per observation, one column per variable. The built-in cars data frame already has this shape.
  2. Write the formula. The response goes on the left of the tilde and the predictors on the right: dist ~ speed. Add predictors with a plus sign for multiple linear regression.
  3. Call lm() and store the result. Assign it to a name so that you can query it repeatedly. The call is shown below.
  4. Print the object to see the call and the estimated coefficients, then call summary() for the full table.
  5. Plot the data and add the fitted line with abline().
fit = lm(dist ~ speed, data = cars)
fit
summary(fit)

plot(cars$speed, cars$dist)
abline(fit)

The abline documentation states that its reg argument takes a regression object with a coef method, that the first two coefficients are used as intercept and slope, and that abline(z) is equivalent to abline(reg = z) for z = lm(dist ~ speed, data = cars) (R documentation: abline). That is why a single abline(fit) draws the line for a one-predictor model. With several predictors the line is no longer a full description of the model, so plot residuals or predictions instead.

The lm() arguments that matter

The usage line in the manual is lm(formula, data, subset, weights, na.action, method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, contrasts = NULL, offset, ...). The table lists the arguments you will meet most often and what the manual says about each (R documentation: lm).

Argument What the documentation says
formula The symbolic description of the model to be fitted. A formula has an implied intercept term.
data The optional data frame holding the variables named in the formula.
subset An optional vector specifying a subset of observations to use in the fitting process.
weights If supplied, weighted least squares is used; if not supplied, ordinary least squares is used.
na.action What to do with missing values. The default comes from options(), and the factory default is na.omit; the value na.exclude can be useful.
method Only “qr” is supported for fitting; “model.frame” returns the model frame without fitting.
singular.ok Defaults to TRUE, so a fit with a singular design is allowed rather than stopped.
contrasts An optional list passed on to model.matrix.default.
offset A known component to be included in the linear predictor during fitting.

The return value is an object of class “lm” (or c(“mlm”, “lm”) when the response has several columns). Its components include coefficients, residuals (the response minus the fitted values), fitted.values, rank and df.residual, so fit$residuals and fit$fitted.values work directly (R documentation: lm).

How to read the lm() output and extract R-squared

Printing the fitted object shows only the call and the coefficients. The fuller report comes from summary(), whose signature is summary(object, correlation = FALSE, symbolic.cor = FALSE, ...). It returns a list, and every number in the printed report is an element of that list, so you can take what you need without copying values by hand (R documentation: summary.lm). The data table below this guide collects those components with the extraction code and the documentation’s own description of each.

How to extract R squared from lm in R

Save the summary and take the element named r.squared; take adj.r.squared for the adjusted value.

s = summary(fit)
s$r.squared
s$adj.r.squared

The manual defines r.squared as the fraction of variance explained by the model, computed as 1 minus the sum of squared residuals divided by the sum of squares of the response’s deviations. adj.r.squared is R-squared adjusted for the number of fitted parameters (R documentation: summary.lm).

How to find the R value in linear regression

People asking for the R value usually mean the correlation coefficient r, not R-squared. For a model with one predictor and an intercept, r is the square root of r.squared with the sign of the slope, and you can also get it directly from the data with cor(cars$speed, cars$dist). This is a mathematical identity for simple regression, not something lm() prints on its own: the summary reports R-squared, and for a model with several predictors the square root of r.squared is the multiple correlation, not the correlation with any single predictor.

What the other numbers in summary() mean

  • Coefficients table. s$coefficients is a matrix with one row per coefficient and four columns: estimate, standard error, t value and the two-sided p value. Rows for aliased coefficients are omitted (R documentation: summary.lm). For the meaning of the p value see the entry on the p-value.
  • Residual standard error. s$sigma is the square root of the estimated error variance, the weighted sum of squared residuals divided by n – p, where n is the number of observations and p the number of fitted coefficients.
  • F statistic. s$fstatistic is a vector of three numbers, the F value and its numerator and denominator degrees of freedom. It is present only for models that have terms other than an intercept.
  • Degrees of freedom. s$df holds three numbers: the number of fitted coefficients, the residual degrees of freedom and the number of non-aliased coefficients.
  • Covariance of the estimates. s$cov.unscaled multiplied by the error variance gives the covariance matrix of the estimated coefficients.

For interval estimates, confint(fit) has a method for “lm” objects and takes parm and level arguments, with a default level of 0.95 (R documentation: confint). An introduction to what an interval does and does not say is in the entry on the confidence interval.

Worked example: every number computed by hand

This is an illustrative composite: a five-point data set invented for the demonstration, not data from any study. It is small enough to check the definitions above by arithmetic. Let x = 1, 2, 3, 4, 5 and y = 2, 4, 5, 4, 5, and fit lm(y ~ x).

  1. The means are 3 for x and 4 for y. The sum of cross-products of deviations is 6 and the sum of squared x deviations is 10, so the slope is 6/10 = 0.6 and the intercept is 4 – 0.6 × 3 = 2.2.
  2. The fitted values are 2.8, 3.4, 4.0, 4.6 and 5.2, so the residuals are -0.8, 0.6, 1.0, -0.6 and -0.2. Their squares sum to 2.4.
  3. The sum of squares of y about its mean is 6, so r.squared = 1 – 2.4/6 = 0.6.
  4. With n = 5 observations and p = 2 coefficients, adj.r.squared = 1 – (1 – 0.6) × 4/3 = 0.4667 (rounded) and sigma = √(2.4/3) = √0.8 = 0.8944 (rounded).
  5. The F statistic is 0.6 / ((1 – 0.6)/3) = 4.5 on 1 and 3 degrees of freedom, and the correlation is √0.6 = 0.7746 (rounded).

These are the quantities summary() reports as r.squared, adj.r.squared, sigma and fstatistic. Running the call on your own copy of this data and comparing the printed values with the arithmetic above is a quick way to confirm that you are extracting the right element.

Is an R-squared value of 0.99 good?

R-squared of 0.99 means the model accounts for 99 percent of the variance in the response in the data it was fitted to; it does not by itself say the model is good, correct or useful. The documentation defines the statistic only as the fraction of variance explained, and its value depends on how the model was fitted: with an intercept the total variation is measured around the mean of y, while in a model without an intercept the centring is zero, so the resulting R-squared is not comparable with an intercept model’s (R documentation: summary.lm). Whether 0.99 is plausible or suspicious depends on your measurement process, because some physical calibrations produce values that high routinely and many behavioural measures never do. Treat it as one number to read alongside the residuals, the adjusted value, the sample size and your own knowledge of the system, and plot the residuals rather than relying on the headline figure.

Predictions, residuals and plots from the same object

Once the model is stored, further work is a function call away. The predict method for “lm” objects takes newdata, an optional data frame, and an interval argument that can be “none”, “confidence” or “prediction”, with a default level of 0.95. If newdata is omitted, the fitted values are used (R documentation: predict.lm).

predict(fit, newdata = data.frame(speed = c(10, 20)), interval = "prediction")
confint(fit)
plot(fit$fitted.values, fit$residuals)

The first call returns predictions for two new speeds with prediction intervals; the second returns coefficient intervals; the third plots residuals against fitted values, the usual first check for curvature or changing spread.

Troubleshooting lm() problems

Missing values change the number of observations

The na.action default is na.omit, so rows with missing values in any variable of the formula are dropped before fitting. Your residual degrees of freedom then reflect fewer rows than the data frame has. The manual notes that na.exclude can be useful, and it is the option to consider when you want residuals and fitted values to line up with the original rows (R documentation: lm).

A coefficient is missing from the table

Because singular.ok is TRUE by default, lm() will fit a model whose predictors are perfectly collinear rather than stop, and summary() omits the aliased coefficients from its coefficients matrix. If a coefficient you expected is absent, check whether one predictor is an exact combination of others. The rank component of the fitted object counts the coefficients that were actually estimated.

R-squared looks wrong after removing the intercept

This is the no-intercept behaviour described above: without an intercept the sums of squares are not centred on the mean, and the statistic answers a different question. Compare models on residual standard error or on out-of-sample prediction instead of comparing R-squared across the two forms.

The F statistic is absent

fstatistic is returned only for models with terms other than an intercept. An intercept-only model has nothing to test, so the element is not there.

Weighted data

If you supply weights, lm() uses weighted least squares, and the summary’s sigma uses the weighted squared residuals, so its values are not interchangeable with an unweighted fit on the same data.

Free alternatives to lm() in R

The table compares lm() with the ordinary least squares class in the Python statsmodels library, using the statsmodels documentation page for OLS.

Tool Function Intercept behaviour in the documentation
R (stats package) lm(formula, data, ...) A formula has an implied intercept term (R documentation: lm).
Python statsmodels statsmodels.regression.linear_model.OLS, with OLS.from_formula for R-style formulas An intercept is not included by default; add one with statsmodels.tools.add_constant, and no constant is added by the model unless you use formulas (statsmodels: OLS).
R (generalised models) glm() For non-normal responses, covered in the modelling guide linked above.

The statsmodels default is the one most likely to cause an apparent discrepancy if you move an analysis between the two tools: a model fitted without the constant gives different coefficients and a different R-squared, as described above.

Frequently asked questions

What is lm in R programming?

lm is the function in R’s stats package that fits linear models by least squares. You supply a formula and a data frame and it returns an “lm” object with coefficients, residuals and fitted values (R documentation: lm).

Is an R-squared value of 0.99 good?

It means 99 percent of the variance of the response in the fitted data is explained by the model. Whether that is good depends on the field and on checks such as residual plots, adjusted R-squared and sample size, and the value is not comparable between models with and without an intercept.

How to extract r squared from lm in R?

Use summary(fit)$r.squared, or summary(fit)$adj.r.squared for the adjusted value.

How to find the R value in linear regression?

For a one-predictor model with an intercept, take the square root of r.squared and give it the sign of the slope, or compute cor(x, y) directly. lm() reports R-squared rather than r.

How do I add the fitted line to a plot?

Draw the scatter plot, then call abline(fit). abline takes the first two coefficients of the regression object as intercept and slope (R documentation: abline).

Sources

Data: Components of summary(lm) in R: where each reported number is stored

Compiled from the R reference manual pages for lm and summary.lm: for each component of the object returned by summary() on an lm fit, the code that extracts it and the documentation's description of what it holds.

Components of summary(lm) in R: where each reported number is stored
ComponentExtraction codeDocumented meaning
r.squaredsummary(fit)$r.squaredFraction of variance explained by the model: 1 minus residual sum of squares over the sum of squares of the response deviations.
adj.r.squaredsummary(fit)$adj.r.squaredR-squared adjusted for the number of fitted parameters.
sigmasummary(fit)$sigmaSquare root of the estimated error variance (weighted squared residuals divided by n - p).
coefficientssummary(fit)$coefficientsp x 4 matrix of estimate, standard error, t value and two-sided p value; aliased coefficients omitted.
fstatisticsummary(fit)$fstatisticThree numbers: F value, numerator df, denominator df; only for models with terms other than an intercept.
dfsummary(fit)$dfThree numbers: p, n - p and the number of non-aliased coefficients.
cov.unscaledsummary(fit)$cov.unscaledp x p matrix; multiplied by the error variance it gives the covariance of the estimates.

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about lm in R: Fit a Linear Model and Read the Output

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →