# Motorcycle data # Load the MASS package; data are in mcycle library(MASS) attach(mcycle) plot(mcycle) par(mfrow=c(2,1)) # Fit orthogonal polynomials plot(mcycle) for(k in 2:6) lines(mcycle$times, predict(lm(accel~poly(times,k)), data=mcycle), lty=k-1) title(sub = "Polynomial fits of degrees 2,...,6 to motorcycle data") plot(mcycle) lines(mcycle$times, predict(lm(accel~poly(times,20)), data=mcycle)) title(sub = "Polynomial fit of degree 20 (!) to motorcycle data") # Fit a Fourier series t = times omega = 2*pi/(max(t)-min(t)) fourierx = function(maxorder) { x = cbind(sin(omega*t), cos(omega*t)) for (k in 2:maxorder) x = cbind(x, sin(k*omega*t), cos(k*omega*t)) } plot(mcycle) lines(times, predict(lm(accel ~ fourierx(2)), data=mcycle$times), lty=1) lines(times, predict(lm(accel ~ fourierx(5)), data=mcycle$times), lty=2) legend("topleft", legend = c("K=2", "K=5"), lty=c(1,2)) plot(mcycle) lines(times, predict(lm(accel ~ fourierx(8)), data=mcycle$times), lty=1) lines(times, predict(lm(accel ~ fourierx(11)), data=mcycle$times), lty=2) legend("topleft", legend = c("K=8", "K=11"), lty=c(1,2)) # Fit a smoothing spline par(mfrow=c(1,1)) fit = smooth.spline(times, accel) plot(mcycle) lines(fit, col=1, lty=1) lines(smooth.spline(times, accel, df=2), col=2, lty=2) lines(smooth.spline(times, accel, df=5), col=4, lty=4) lines(smooth.spline(times, accel, df=60), col=6, lty=6) legend("bottomright", legend = c("df=12.21 (GCV)", "df=2", "df=5", "df=60"), col=c(1,2,4,6), lty=c(1,2,4,6))