### R code for Section 8.3-2 and 8.3-3 ## Example 8.3-2 on page 464 ## read table 8.3-1 on page 464 data = read.table("table831.dat", head=T) y = data[,1] x = data[,2] fit0 = lm(y~x) summary(fit0) # scatter plot and residual plot par(mfrow=c(1,2)) plot(x,y,xlab="Temperature",ylab="Steam", main="Scatter Plot") abline(fit0$coef[1],fit0$coef[2]) plot(fit0$fitted,fit0$residual,xlab="Fitted value",ylab="Residual", main="Residual Plot") abline(0,0) # plot residual versus lagged residuals n = length(x) # number of observations r = fit0$residual # residuals par(mfrow=c(1,1)) plot(r[1:(n-1)], r[2:n], xlab="Lagged residual", ylab="Residual", main="Lagged Residual Plot") temp = lm(r[2:n]~r[1:(n-1)]) abline(temp$coef[1],temp$coef[2]) # lag 1 autocorrelation r1 = sum(r[1:(n-1)]*r[2:n])/sum(r^2) # Durbin-Watson test # need to install R package "lmtest" first, go to R menu "Packages" ==> "Install package(s)..." library("lmtest") dwtest(y~x) ## read data set "exercise832.dat" data = read.table("exercise832.dat", head=T) X = data$X Y1 = data$Y1 Y2 = data$Y2 Y3 = data$Y3 X4 = data$X4 Y4 = data$Y4 ## linear regression fit1 = lm(Y1~X) fit2 = lm(Y2~X) fit3 = lm(Y3~X) fit4 = lm(Y4~X4) ## scatter plots par(mfrow=c(2,2)) plot(c(0,20), c(0,15), xlab="X", ylab="Y1", main="(a)", type="n") points(X, Y1) abline(fit1$coef[1], fit1$coef[2]) plot(c(0,20), c(0,15), xlab="X", ylab="Y2", main="(b)", type="n") points(X, Y2) abline(fit2$coef[1], fit2$coef[2]) plot(c(0,20), c(0,15), xlab="X", ylab="Y3", main="(c)", type="n") points(X, Y3) abline(fit3$coef[1], fit3$coef[2]) plot(c(0,20), c(0,15), xlab="X4", ylab="Y4", main="(d)", type="n") points(X4,Y4) abline(fit4$coef[1], fit4$coef[2]) ## plot fitted results par(mfrow=c(2,3)) for(i in 1:6) plot(fit1, i); ## Cook's distance par(mfrow=c(2,2)) plot(fit1, 4, main="(a)") plot(fit2, 4, main="(b)") plot(fit3, 4, main="(c)") plot(fit4, 4, main="(d)") ## calculate Cook's distance directly cooks.distance(fit1)