Front
Back
What does lm() do and how do you use it?
Fits linear models via OLS for regression and inference.
Code:
fit <- lm(mpg ~ wt + hp, data = mtcars)
summary(fit); confint(fit)
predict(fit, newdata = data.frame(wt=3, hp=110), interval=’prediction’)
Notes:
Check assumptions with residual diagnostics (plot(fit), qqnorm/qqline).
How do you fit a logistic regression with glm()?
Use glm(family = binomial) for binary outcomes.
Code:
fit <- glm(am ~ mpg + wt, data = mtcars, family = binomial())
summary(fit)
predict(fit, newdata = mtcars, type = ‘response’) # probabilities
Notes:
Interpret coefficients on log-odds scale; use broom::tidy() for tidy output.
How do you compare nested models? (anova, AIC/BIC)
Use anova(m1, m2) and AIC/BIC for information criteria.
Code:
m1 <- lm(mpg ~ wt, data=mtcars)
m2 <- lm(mpg ~ wt + hp, data=mtcars)
anova(m1, m2); AIC(m1, m2); BIC(m1, m2)
How do you extract fitted values and residuals?
Use fitted() and residuals().
Code:
fit <- lm(mpg ~ wt, data = mtcars)
head(fitted(fit)); head(residuals(fit))