lm( )

Fit linear regression models. lm() is part of base R (stats package).

Required Library

# lm() is in base R (stats), loaded by default — no package installation needed

Syntax

lm(y ~ x, data = df)

# Pipe style (common in tidyverse workflows)
df %>% lm(y ~ x, data = .)

lm(y ~ x, data = df) fits a straight-line model in the form y = ax + b, where a is slope and b is intercept. In formula syntax, the left side is the response and the right side is the predictor(s).

lm(y ~ 0 + x, data = df)
lm(y ~ x - 1, data = df)

The above variants fit a zero-intercept model (forced through the origin). Use this only when the scientific model justifies it.

lm() returns a model object. Use helper functions to extract what you need:

  • coef(model) for intercept and slope
  • summary(model)$r.squared for goodness of fit
  • predict(model, newdata = ...) for predictions

Examples

Fit a calibration line and extract slope/intercept
Extract R-squared and inspect model summary
Predict absorbance at new concentration values
Add the fitted lm() line to a ggplot with geom_abline()
Compare free-intercept and zero-intercept models

Argument Overview

Required arguments must be included when using a function while optional arguments can be included on demand.

formula — model formula formula Required

Specifies the model structure, usually y ~ x for simple linear regression. Left side is the response variable; right side is the predictor.

lm(absorbance ~ conc_ug_ml, data = calibration)
lm(absorbance ~ 0 + conc_ug_ml, data = calibration)

Data Types: formula

data — data frame containing variables data frame | tibble Optional

Data source used to evaluate variables in the formula.

This argument can be omitted, but then the variables in the formula (for example y and x) must already exist as objects in your environment.

lm(absorbance ~ conc_ug_ml, data = calibration)

# Also valid if absorbance and conc_ug_ml already exist as standalone vectors:
lm(absorbance ~ conc_ug_ml)

Data Types: data.frame | tibble

subset — rows to include in fit logical | integer Optional

Fits the model on a selected subset of rows.

lm(absorbance ~ conc_ug_ml, data = calibration, subset = conc_ug_ml <= 20)

Data Types: logical or integer row index · Default: all rows

weights — observation weights numeric Optional

Relative weights for weighted least squares (WLS).

lm(absorbance ~ conc_ug_ml, data = calibration, weights = wt)

Data Types: numeric vector (same length as observations) · Default: NULL

na.action — missing-value handling function Optional

Controls how missing values are handled during model fitting.

lm(absorbance ~ conc_ug_ml, data = calibration, na.action = na.exclude)

Data Types: function (for example na.omit, na.exclude) · Default: session option