Hands-on: k-NN Regression with S3 OOP

Overview

In this 30 min session you will:

  • Load and inspect the knn_s3 and knn_s3_formula scripts
  • Fit k-NN regression models using S3
  • Use print(), summary(), fitted(), predict(), anova()

Setup

Download the scripts:

curl -O https://raw.githubusercontent.com/mmadoliat/WSoRT/refs/heads/main/R/knn_s3.R
curl -O https://raw.githubusercontent.com/mmadoliat/WSoRT/refs/heads/main/R/knn_s3_formula.R

Source them in your R console:

source("R/knn_s3.R")
source("R/knn_s3_formula.R")

Example Code

# Fit two models
mod5  <- knn_s3(mpg ~ disp + hp + wt, mtcars, k = 5)
mod10 <- knn_s3(mpg ~ disp + hp + wt, mtcars, k = 10)

# Inspect models
print(mod5)
summary(mod5)
fitted(mod5)[1:5]

# Compare models
anova(mod5, mod10)

Tasks

  1. Vary k: change k to 3 and 8, then re-run summary().
  2. Backend swap: use predict(mod5, head(mtcars), method="R") and compare.
  3. New predictor: fit a model with mpg ~ cyl + gear and compare with the first via anova().

Good luck!