Linear regression in R
Fitting a linear model with the formula interface.
set.seed(5)
data <- data.frame(
hours = rnorm(60, 20, 5),
caffeine = runif(60, 0, 4)
)
data$score <- 40 + 2.5 * data$hours + 3 * data$caffeine + rnorm(60, sd = 6)
model <- lm(score ~ hours + caffeine, data = data)
coefs <- coef(model)
r_squared <- summary(model)$r.squared
residuals <- resid(model)
predictions <- fitted(model)
How it works
score ~ hours + caffeinenames outcome and predictors.coefreads the fitted coefficients.summary(model)$r.squared,resid, andfittedassess it.
Keywords and builtins used here
coeffittedlmresidrnormrunifsummary
The run, in numbers
- Lines
- 13
- Characters to type
- 329
- Tokens
- 96
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 58 seconds.
Step 2 of 4 in Correlation & regression, step 7 of 11 in Statistics.