## Chapter 5: Regression with a Single Predictor 

## Sec 5.1: Fitting a Line to Data 
##                     How accurate is the line? 
## ss 5.1.1: Summary information -- lawn roller example 
## Footnote Code
## Global options used for this and most later output 
options(show.signif.stars=FALSE, digits=4) 
  # show.signif.stars=FALSE suppresses interpretive features that, 
  # for our use of the output, are unhelpful. 

library(DAAG) 
## Loading required package: lattice
## Fit lm model: data from roller (DAAG); output in roller.lm 
roller.lm <- lm(depression ~ weight, data = roller) 
## Use the extractor function summary() to summarize results  
summary(roller.lm) 
## 
## Call:
## lm(formula = depression ~ weight, data = roller)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
##  -8.18  -5.58  -1.35   5.92   8.02 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)    -2.09       4.75   -0.44   0.6723
## weight          2.67       0.70    3.81   0.0052
## 
## Residual standard error: 6.74 on 8 degrees of freedom
## Multiple R-squared:  0.644,  Adjusted R-squared:   0.6 
## F-statistic: 14.5 on 1 and 8 DF,  p-value: 0.00518
## Footnote Code
## Fit model that omits intercept term; i.e., y = bx 
lm(depression ~ -1 + weight, data=roller) 
## 
## Call:
## lm(formula = depression ~ -1 + weight, data = roller)
## 
## Coefficients:
## weight  
##   2.39
## ss 5.1.2: Residual plots 
## A: Plot residuals vs fitted values; B: normal probability plot 
plot(roller.lm, which = 1:2) 

plot of chunk unnamed-chunk-1plot of chunk unnamed-chunk-1

## Footnote Code
## Alternatively, use the following code: 
test <- residuals(roller.lm); n <- length(test) 
av <- mean(test); sdev <- sd(test)  
y <- c(test, rnorm(7*n, av, sdev)) 
fac <- c(rep("residuals(roller.lm)",n), paste("reference", rep(1:7, rep(n,7)))) 
fac <- factor(fac, levels=unique(fac)) 
library(lattice) 
qqmath(~ y|fac, aspect=1, layout=c(4,2)) 

plot of chunk unnamed-chunk-1

## Normal probability plot, plus 7 reference plots 
qreference(residuals(roller.lm), nrep=8, nrows=2) 

plot of chunk unnamed-chunk-1

## ss 5.1.3: Iron slag example: is there a pattern in the residuals? 
## Footnote Code
## Panel A: chemical vs magnetic (Data frame ironslag from DAAG) 
plot(chemical ~ magnetic, data=ironslag) 
ironslag.lm <- lm(chemical ~ magnetic, data=ironslag) 
abline(ironslag.lm) 
with(ironslag, lines(lowess(chemical ~ magnetic, f=.9), lty=2)) 

plot of chunk unnamed-chunk-1

## Footnote Code
## Panel B: Residuals from straight line fit, vs magnetic 
res <- residuals(ironslag.lm) 
plot(res ~ magnetic, xlab="Residual", data=ironslag) 
with(ironslag, lines(lowess(res ~ magnetic, f=.9), lty=2))