GAM Exercises in R: 15 Practice Problems

Fifteen practice problems on Generalized Additive Models in R: mgcv, smooth terms, splines, interaction smooths, predict. Hidden solutions.

RRun this once before any exercise
library(mgcv) library(dplyr)

  

Exercise 1: Simple GAM

Difficulty: Intermediate.

Show solution
RInteractive R
gam(mpg ~ s(wt), data = mtcars)

  

Exercise 2: Two smooth terms

Difficulty: Intermediate.

Show solution
RInteractive R
gam(mpg ~ s(wt) + s(hp), data = mtcars)

  

Exercise 3: Linear + smooth

Difficulty: Intermediate.

Show solution
RInteractive R
gam(mpg ~ wt + s(hp), data = mtcars)

  

Exercise 4: Set basis dimension

Difficulty: Advanced.

Show solution
RInteractive R
gam(mpg ~ s(wt, k = 5), data = mtcars)

  

Exercise 5: Tensor product (interaction smooth)

Difficulty: Advanced.

Show solution
RInteractive R
gam(mpg ~ te(wt, hp), data = mtcars)

  

Exercise 6: GAM with categorical

Difficulty: Advanced.

Show solution
RInteractive R
gam(mpg ~ s(wt) + factor(cyl), data = mtcars)

  

Exercise 7: Different smooth basis (cr)

Difficulty: Advanced.

Show solution
RInteractive R
gam(mpg ~ s(wt, bs = "cr"), data = mtcars)

  

Exercise 8: Smooth by group

Difficulty: Advanced.

Show solution
RInteractive R
gam(mpg ~ s(wt, by = factor(cyl)) + factor(cyl), data = mtcars)

  

Exercise 9: Plot a smooth

Difficulty: Intermediate.

Show solution
RInteractive R
fit <- gam(mpg ~ s(wt), data = mtcars) plot(fit)

  

Exercise 10: Summary

Difficulty: Intermediate.

Show solution
RInteractive R
fit <- gam(mpg ~ s(wt) + s(hp), data = mtcars) summary(fit)

  

Exercise 11: Predict new

Difficulty: Intermediate.

Show solution
RInteractive R
fit <- gam(mpg ~ s(wt), data = mtcars) predict(fit, newdata = data.frame(wt = c(2.5, 4)))

  

Exercise 12: Edf (effective df)

Difficulty: Advanced.

Show solution
RInteractive R
fit <- gam(mpg ~ s(wt), data = mtcars) summary(fit)$edf

  

Exercise 13: Concurvity (GAM collinearity)

Difficulty: Advanced.

Show solution
RInteractive R
fit <- gam(mpg ~ s(wt) + s(hp), data = mtcars) concurvity(fit)

  

Exercise 14: GAM for binary outcome

Difficulty: Advanced.

Show solution
RInteractive R
gam(am ~ s(mpg) + s(hp), data = mtcars, family = binomial)

  

Exercise 15: Check residuals

Difficulty: Intermediate.

Show solution
RInteractive R
fit <- gam(mpg ~ s(wt), data = mtcars) gam.check(fit)

  

What to do next

  • Linear-Regression-Exercises (shipped), linear baseline.
  • Mixed-Effects-Models-Exercises (shipped), hierarchical alternative.

Ready to earn the GAM Certificate?

The quiz is concept-based and respects your time: pass it once and your verifiable certificate is yours to share on LinkedIn, your resume, or your portfolio. Take it when you feel comfortable with the material.

Attempt the quiz