# # Exercise in Class # # AGRESTI (2015) Foundations of Linear and Generalized Linear Models # # Each year the Scottish Hill Runners Association (www.shr.uk.com) # publishes a list of hill races in Scotland for the year. # # Data on the record time for some of the races (in minutes). # Explanatory variables listed are the distance of the race (in miles) # and the cumulative climb (in thousands of feet). # x<-scan() 2.5 2.5 6 7.5 8 16 28 y<-scan() 16.08 17.50 33.65 45.60 62.27 204.62 192.67 cbind(x,y) cbind(x,y,x*y,x*x) cbind(sum(x),sum(y),sum(x*y),sum(x*x)) cbind(mean(x),mean(y)) n<-length(x) Sxy<-sum(x*y)-sum(x)*sum(y)/n Sxx<-sum(x*x)-sum(x)^2/n b1<-Sxy/Sxx b0<-mean(y)-b1*mean(x) cat("Y=",b0,"+",b1,"*X","\n") plot(x,y,pch=16,xlim=c(0,30),ylim=c(0,230)) abline(a=b0,b=b1,col=2,lwd=2) summary(lm(y~x)) abline(lm(y~x),lwd=2) predict(lm(y~x),list(x=c(2.5,20))) yhat<-fitted(lm(y~x)) cbind(x,y,yhat,y-yhat) join <- function(i){ lines(c(x[i],x[i]),c(y[i],yhat[i]),col="green")} sapply(1:n,join) lm.yx1<-lm(y~-1+x) summary(lm.yx1) plot(x,y,pch=16,xlim=c(0,30),ylim=c(0,230)) abline(lm.yx1,col=2,lwd=2) # # Full Example # ScotsRaces<-read.table("https://users.stat.ufl.edu/~aa/glm/data/ScotsRaces.dat",header=T) ScotsRaces attach(ScotsRaces) ScotsRaces[order(distance),] pairs(ScotsRaces[2:4]) cor(ScotsRaces[2:4]) summary(lm(time~distance,data=ScotsRaces)) attach(ScotsRaces) plot(distance,time,pch=16,xlim=c(0,30),ylim=c(0,230)) abline(lm(time~distance)) summary(lm(time~-1+distance)) plot(distance,time,pch=16,xlim=c(0,30),ylim=c(0,230)) abline(lm(time~-1+distance)) summary(lm(time~distance+climb)) summary(lm(time~-1+distance+climb))