# R example for Weighted Least Squares # We use the blood pressure data in Table 11.1 of the book # Save the data file into a directory and # use the full path name: bloodpressure.data <- read.table(file = "z:/My Documents/teaching/stat_704/bloodpressuredata.txt", header=FALSE, col.names = c('age', 'dbp')) # attaching the data frame: attach(bloodpressure.data) # Regressing the response, dbp, against the predictor, age bp.reg <- lm(dbp ~ age) # The plots show some definite nonconstant error variance plot(age, dbp); abline(bp.reg) plot(age, resid(bp.reg)); abline(h=0) # Plot of absolute residuals against age shows that # absolute residuals may increase linearly with age. abs.res <- abs(resid(bp.reg)) plot(age, abs.res) # Regressing the absolute residuals against the predictor, age bp.reg2 <- lm(abs.res ~ age) # Defining the weights using the fitted values from this second regression: weight.vec <- 1/((fitted(bp.reg2))^2); # Using the weights option in lm to get the WLS estimates: bp.wls.reg <- lm(dbp ~ age, weights = weight.vec) summary(bp.wls.reg) # A residual plot for the WLS regression: plot(age, resid(bp.wls.reg)); abline(h=0)