lm fits a linear model from a formula. Coefficients summarize the fitted relationship.

Program

Play the script to fit a straight line and read its slope.

linear_model.R
Replay: real traced execution (multi-file project)
x <- c(1, 2, 3)
y <- c(2, 4, 6)
fit <- lm(y ~ x)
slope <- coef(fit)[["x"]]
cat(slope, "\n", sep = "")
  1. x ← 1, 2, 3

    1x <- c(1, 2, 3)2y <- c(2, 4, 6)
    values this step1, 2, 3x
  2. y ← 2, 4, 6

    1x <- c(1, 2, 3)2y <- c(2, 4, 6)3fit <- lm(y ~ x)
    values this step2, 4, 6y
  3. fit ← line y ~ x

    2y <- c(2, 4, 6)3fit <- lm(y ~ x)4slope <- coef(fit)[["x"]]
    values this stepline y ~ xfit1, 2, 3x2, 4, 6y
  4. slope ← 2

    3fit <- lm(y ~ x)4slope <- coef(fit)[["x"]]5cat(slope, "\n", sep = "")
    values this step2slope2coef(fit)["x"]
  5. cat(slope, " ", sep = "")

    4slope <- coef(fit)[["x"]]5cat(slope, "\n", sep = "")
    output2
    values this step2slope
lm `lm(y ~ x)` fits a linear model predicting `y` from `x`.
formula `y ~ x` is R formula syntax for model relationships.
coef `coef(fit)` returns fitted model coefficients.