Files and Reproducibility
Linear Models
Formula to Coefficients
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 = "")
x ← 1, 2, 3
1x <- c(1, 2, 3)2y <- c(2, 4, 6)values this step1, 2, 3xy ← 2, 4, 6
1x <- c(1, 2, 3)2y <- c(2, 4, 6)3fit <- lm(y ~ x)values this step2, 4, 6yfit ← line y ~ x
2y <- c(2, 4, 6)3fit <- lm(y ~ x)4slope <- coef(fit)[["x"]]values this stepline y ~ xfit1, 2, 3x2, 4, 6yslope ← 2
3fit <- lm(y ~ x)4slope <- coef(fit)[["x"]]5cat(slope, "\n", sep = "")values this step2slope2coef(fit)["x"]cat(slope, " ", sep = "")
4slope <- coef(fit)[["x"]]5cat(slope, "\n", sep = "")output2values 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.