Get startedGet started for free

Setting complexity of the motorcycle model

The number of basis functions in a smooth has a great impact on the shapes a model can take. Here, you'll practice modifying the number of basis functions in a model and examining the results.

This exercise is part of the course

Nonlinear Modeling with Generalized Additive Models (GAMs) in R

View Course

Exercise instructions

  • Fit a GAM with 3 basis functions to the mcycle data, with accel as a smooth function of times.
  • Fit the same GAM again, but this time with 20 basis functions.
  • Use the provided plot() functions to visualize both models.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

library(mgcv)

# Fit a GAM with 3 basis functions
gam_mod_k3 <- gam(accel ~ s(times, k = ___), data = mcycle)

# Fit with 20 basis functions
gam_mod_k20 <- gam(___)

# Visualize the GAMs
par(mfrow = c(1, 2))
plot(gam_mod_k3, residuals = TRUE, pch = 1)
plot(gam_mod_k20, residuals = TRUE, pch = 1)
Edit and Run Code