8.7 Coding Activity:R Cheat Sheet
Suppose x
and y
are variables in dataframe d
.
To fit an ols regression of Y on X:
mod <- lm(y ~ x, data = d)
To access coefficients from the model object:
mod$coefficients
or coef(mod)
To access fitted values from the model object:
mod$fitted
or fitted(mod)
or predict(mod)
To access residuals from the model object:
mod$residuals
or resid(mod)
To create a scatterplot that includes the regression line:
plot(d['x'], d['y'])
abline(mod)
or
d %>%
ggplot() +
aes(x = x, y = y) +
geom_point() +
geom_smooth(method = lm)