Hands-on: k-NN Regression with S3 OOP
Overview
In this 30 min session you will:
- Load and inspect the
knn_s3andknn_s3_formulascripts - 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.RSource 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
- Vary k: change
kto 3 and 8, then re-runsummary(). - Backend swap: use
predict(mod5, head(mtcars), method="R")and compare. - New predictor: fit a model with
mpg ~ cyl + gearand compare with the first viaanova().
Good luck!