# STAT3530 -- leverage, standardized residuals, and influence

site <- 'https://tdruiz-stat3530.share.connect.posit.cloud/_data/'

load(url(paste0(site, 'mammals.RData')))

# --- the model -------------------------------------------------------------
# Hours of sleep per day against lifespan, for 51 mammal species.
fit <- lm(sleep ~ lifespan, data = mammals)

plot(sleep ~ lifespan, data = mammals)
abline(fit, col = 'blue', lwd = 2)

# --- leverage --------------------------------------------------------------
# How far each lifespan is from the center of all the lifespans.
h <- hatvalues(fit)
plot(mammals$lifespan, h, xlab = 'lifespan', ylab = 'leverage')

# look for a point that stands apart from the rest
mammals$species[which.max(h)]

# --- standardized residuals ------------------------------------------------
# Residuals rescaled so that high-leverage points are on the same footing.
r <- rstandard(fit)
plot(fitted(fit), r, xlab = 'fitted value', ylab = 'standardized residual')
abline(h = 0, col = 'red', lty = 2, lwd = 2)

mammals$species[which.max(abs(r))]

# --- Cook's distance -------------------------------------------------------
# How much all the fitted values move when each point is removed.
D <- cooks.distance(fit)
plot(D, type = 'h', xlab = 'observation', ylab = "Cook's distance")

mammals$species[which.max(D)]

# --- refit without the most influential point ------------------------------
fit2 <- lm(sleep ~ lifespan, data = mammals[-which.max(D), ])
rbind(all = coef(fit), without = coef(fit2))

# --- extra practice ---------------------------------------------------------
# The hills data give the record time (minutes) and distance (miles) for 35
# Scottish hill races. They come with the MASS package, and the race names are
# the row names.

data(hills, package = 'MASS')

# 1. Fit the model time ~ dist and plot the data with the fitted line.


# 2. Compute the leverages. Which race stands apart from the rest, and why?


# 3. Compute the standardized residuals. Which races stand apart?


# 4. Compute Cook's distance. Which race is the most influential? Refit the
#    model without it and compare the coefficients.
