######################### # # # STAT 599 Spring 2013 # # # # Example R code # # # # Chapter 12 # # # ######################### ### Installing the add-on packages needed for this course: # If you haven't already done so, # type at the command line (without the preceding # ): # install.packages(c('faraway','mgcv','acepack','mda','brlr','sm','wavethresh','SuppDists','lme4')) # and choose a U.S. mirror site when the window pops up. # This will install the needed packages for you. ###################################### ## # Additive Models ## ###################################### # load the 'faraway' package: library(faraway) # loading the 'ozone' dataset: data(ozone) # attaching the 'ozone' dataset: # attach(ozone) # Ordinary linear model: olm <- lm(O3 ~ temp + ibh + ibt, data=ozone) summary(olm) ## Additive model, using loess to estimate the f_j functions: # load the 'gam' package: library(gam) ozone.gam.loess <- gam(O3 ~ lo(temp) + lo(ibh) + lo(ibt), data=ozone) summary(ozone.gam.loess) # A deviance F-test to check significance of 'ibt' term: ozone.gam.loess.reduced <- gam(O3 ~ lo(temp) + lo(ibh), data=ozone) anova(ozone.gam.loess.reduced, ozone.gam.loess, test="F") # Visualizing the f_j(x_j) functions: plot(ozone.gam.loess, residuals=TRUE, se=TRUE, pch=".", ask=T) ### We could easily do something similar using smoothing splines: ozone.gam.ss <- gam(O3 ~ s(temp) + s(ibh) + s(ibt), data=ozone) summary(ozone.gam.ss) # A deviance F-test to check significance of 'ibt' term: ozone.gam.ss.reduced <- gam(O3 ~ s(temp) + s(ibh), data=ozone) anova(ozone.gam.ss.reduced, ozone.gam.ss, test="F") ### Additive model, using the 'mgcv' package: # load the 'mgcv' package: library(mgcv) ozone.mgcv.ss <- gam(O3 ~ s(temp) + s(ibh) + s(ibt), data=ozone) plot(ozone.mgcv.ss, residuals=TRUE, se=TRUE, pch=".") ## We may safely drop 'ibt' from the model... # A deviance-based F-test to see whether temperature actually enters the model in a linear way: ozone.mgcv.1 <- gam(O3 ~ s(temp) + s(ibh), data=ozone) ozone.mgcv.lin <- gam(O3 ~ temp + s(ibh), data=ozone) anova(ozone.mgcv.lin, ozone.mgcv.1, test="F") #### A test for temp-by-ibh interaction: # Fitting an additive model that allows for interaction: ozone.mgcv.int <- gam(O3 ~ s(temp,ibh) + s(ibt), data=ozone) # Fitting an additive model that does not allow for interaction: ozone.mgcv.ss <- gam(O3 ~ s(temp) + s(ibh) + s(ibt), data=ozone) anova(ozone.mgcv.ss, ozone.mgcv.int, test="F") ## A graphical examination of possible interaction: plot(ozone.mgcv.int) vis.gam(ozone.mgcv.int, theta=-45, color="gray") ## Using the additive-model results to inform a (piecewise linear) parametric model: # Defining "hockey-stick" basis functions: rhs <- function(x,c) ifelse(x>c,x-c,0) lhs <- function(x,c) ifelse(x