# How does pH in Nowegian lakes depend on sulfate, nitrate, calcium, aluminium and organic content (x1, ... x5), area of lake (x6) and location (x7 = 0, Telemark, or x7 = 1, Trøndelag)? Data from Statens forurensningstilsyn (1986). Here 26 random lakes from Telemark and Trøndelag out of 1005 lakes have been drawn 

acidrain <- read.table("http://www.math.ntnu.no/~mettela/TMA4267/Data/acidrain.txt",header=TRUE)

fit <- lm(y~.,data=acidrain) # lm: linear model

# scatter plots
pairs(acidrain)

plot(fit$fitted.values,fit$residuals)

rres <- rstudent(fit) # externally studentized residuals
plot(fit$fitted.values,rres)
# seems OK

# if not OK, plot each x vs. studentized residuals
attach(acidrain)
plot(x7,rres)

# normality of residuals
qqnorm(rres)
qqline(rres)
library(nortest)
ad.test(rres) # Anderson-Darling test
# normality test not used in general - low power for small samples, and small deviations give rejections for large samples

# Kolmogorov-Smirnov tests
ks.test(rres,"pt",26-8-1) # residuals from t(17)?
ks.test(rres,"pnorm") # residuals from N(0,1)?

# built-in plots
par(mfrow=c(2,2))
plot(fit)

# transformations
library(MASS)
boxcox(fit)
boxcox(fit,lambda=seq(-5,5,.1))
