Fit linear regression with lm() using formula syntax—y ~ x1 + x2. R's formula interface is a core strength vs generic scripting in Python.
Simple regression
df <- data.frame(x = 1:5, y = c(2.1, 4.2, 5.8, 8.1, 10.0))
fit <- lm(y ~ x, data = df)
print(summary(fit))
Coefficients and fitted values
print(coef(fit))
print(fitted(fit))
Important interview questions and answers
- Q: Formula y ~ x meaning?
A: Model y as linear function of x plus intercept—R expands factors automatically. - Q: summary(fit) shows?
A: Coefficients, standard errors, t-tests, R-squared—diagnostics come next lesson.
Self-check
- What function fits linear models?
- How access model coefficients?
Tip: Formula y ~ x1 + x2 expands factors automatically—inspect summary(fit) coefficient names.
Interview prep
- lm output?
Coefficients, residuals, fitted values, and model call—use
summary()for inference.