typestar

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

  1. score ~ hours + caffeine names outcome and predictors.
  2. coef reads the fitted coefficients.
  3. summary(model)$r.squared, resid, and fitted assess it.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Correlation & regression, step 7 of 11 in Statistics.

← Previous Next →

Linear regression in other languages