Appendix B — R Practicals

This appendix gives a complete set of laboratory exercises covering the practical syllabi of STAT 567 (Regression Analysis) and STAT 521 (Applied Regression Analysis). Each practical lists its objective, the data set (in the csv/ folder of the book repository), the R code, and questions to be answered in the practical record. The chapter in which the method is explained is given in brackets.

Before starting, set the working directory to the book folder (or an R project containing the csv/ folder) and install the required packages once:

install.packages(c("MASS", "car", "lmtest", "nlme"))

B.1 Practical 1: Correlation coefficients and their tests (Chapter 2)

Objective. Compute simple, rank, partial and multiple correlations and test their significance.

rc <- read.csv("csv/ricecomp.csv")
cor(rc)                                         # correlation matrix
cor.test(rc$yield, rc$prodtill)                 # H0: rho = 0
cor.test(rc$yield, rc$prodtill, method = "spearman", exact = FALSE)
z <- atanh(cor(rc$yield, rc$grains)); n <- nrow(rc)
(z - atanh(0.3)) * sqrt(n - 3)                  # H0: rho = 0.3 (Fisher z)
Ri <- solve(cor(rc)); -Ri[1, 3] / sqrt(Ri[1, 1] * Ri[3, 3])   # r(yield, tillers . rest)
1 - 1 / Ri[1, 1]                                # R^2 of yield on all others

Questions. (a) Which yield component has the highest simple correlation with yield? (b) Compare the simple and partial correlations of yield with tillers, and explain the difference. (c) Test the multiple correlation of yield with all components.

B.2 Practical 2: Simple linear regression (Chapter 3)

nt  <- read.csv("csv/nitrogen.csv")
fit <- lm(yield ~ N, data = nt)
summary(fit); anova(fit); confint(fit)
predict(fit, data.frame(N = c(50, 100, 150)), interval = "confidence")
predict(fit, data.frame(N = c(50, 100, 150)), interval = "prediction")

Questions. (a) Write the fitted equation and interpret the slope. (b) Verify \(t^2=F\). (c) Why is the prediction interval wider than the confidence interval?

B.3 Practical 3: Multiple regression with three and four regressors in matrix form (Chapter 4)

pd <- read.csv("csv/paddy.csv")
y  <- pd$yield
X3 <- cbind(1, pd$N, pd$P, pd$K)                 # three regressors
X4 <- cbind(X3, pd$OC)                          # four regressors
for (X in list(X3, X4)) {
  b  <- solve(crossprod(X), crossprod(X, y))
  e  <- y - X %*% b; n <- nrow(X); p <- ncol(X)
  s2 <- sum(e^2) / (n - p)
  print(round(cbind(b, sqrt(diag(s2 * solve(crossprod(X))))), 4))
}
summary(lm(yield ~ N + P + K + OC, data = pd))   # check

Questions. (a) Compute \(\mathbf X'\mathbf X\), \((\mathbf X'\mathbf X)^{-1}\), \(\hat{\boldsymbol\beta}\), \(s^2\) and the standard errors by hand for the three-regressor model and verify with lm(). (b) How does adding OC change the coefficients of N, P and K? Why?

B.4 Practical 4: Standardized regression coefficients (Chapter 6)

d12 <- read.csv("csv/notes12.csv")
coef(lm(y ~ x1 + x2 - 1, data = as.data.frame(scale(d12))))
solve(cor(d12[, -1]), cor(d12[, -1], d12$y))

Questions. (a) Obtain the standardized coefficients by unit normal and unit length scaling. (b) Recover the original coefficients.

B.5 Practical 5: Testing hypotheses, sub-hypotheses and restricted estimation (Chapter 7)

pd   <- read.csv("csv/paddy.csv")
full <- lm(yield ~ N + P + K, data = pd)
anova(lm(yield ~ N, data = pd), full)          # H0: beta_P = beta_K = 0
car::linearHypothesis(full, "P = K")           # H0: beta_P = beta_K
XtXi <- solve(crossprod(model.matrix(full)))
C <- matrix(c(0, 0, 1, -1), 1); b <- coef(full)
bR <- b - XtXi %*% t(C) %*% solve(C %*% XtXi %*% t(C)) %*% (C %*% b)
cbind(unrestricted = b, restricted = drop(bR))

Questions. (a) Construct the ANOVA table and compute \(R^2\) and adjusted \(R^2\). (b) Test the sub-hypotheses. (c) Obtain and interpret the restricted estimates.

B.6 Practical 6: Residuals, outlier detection and distribution of residuals (Chapter 8)

fit <- lm(yield ~ N + P + K, data = read.csv("csv/paddy.csv"))
res <- data.frame(e = resid(fit), d = resid(fit) / sigma(fit),
                  r = rstandard(fit), t = rstudent(fit), h = hatvalues(fit))
res$press <- res$e / (1 - res$h)
round(res, 3)
sum(res$press^2)                                # PRESS
car::outlierTest(fit)
qqnorm(res$r); qqline(res$r); hist(res$r)

Questions. (a) Which observations have \(|d_i|>3\) or \(|t_i|\) beyond the Bonferroni limit? (b) Compute \(R^2_{\text{prediction}}\). (c) Comment on the distribution of the residuals.

B.7 Practical 7: Tests of normality and homoscedasticity; lack of fit (Chapter 8)

fit <- lm(yield ~ N + P + K, data = read.csv("csv/paddy.csv"))
shapiro.test(rstandard(fit))
lmtest::bptest(fit)
nd <- read.csv("csv/ndose.csv")
anova(lm(yield ~ N, data = nd), lm(yield ~ factor(N), data = nd))   # lack of fit

B.8 Practical 8: Leverage and influence (Chapter 9)

fit <- lm(yield ~ N + P + K, data = read.csv("csv/paddy.csv"))
summary(influence.measures(fit))
car::influencePlot(fit)

Questions. (a) List the observations exceeding each cut-off. (b) Verify Cook’s \(D\) for the most influential farm by refitting without it.

B.9 Practical 9: Handling correlated errors (Chapter 10)

cc  <- read.csv("csv/coconut.csv")
fit <- lm(nuts ~ rainfall, data = cc)
lmtest::dwtest(fit)
n <- nrow(cc); e <- resid(fit); rho <- sum(e[-1] * e[-n]) / sum(e[-n]^2)
fco <- lm(I(nuts[-1] - rho * nuts[-n]) ~ I(rainfall[-1] - rho * rainfall[-n]), data = cc)
lmtest::dwtest(fco)

Questions. (a) Compute \(d\) by hand and apply the bounds test. (b) Carry out the Cochrane–Orcutt iterations to convergence.

B.10 Practical 10: Multicollinearity (Chapter 11)

rc  <- read.csv("csv/ricecomp.csv")
fit <- lm(yield ~ ., data = rc)
car::vif(fit); ev <- eigen(cor(rc[, -1]))$values; max(ev) / min(ev)
MASS::select(MASS::lm.ridge(yield ~ ., data = rc, lambda = seq(0, 10, 0.1)))

B.11 Practical 11: Weighted least squares and Box–Cox transformation (Chapter 12)

inp <- read.csv("csv/inputs.csv")
summary(lm(expend ~ size, data = inp, weights = 1 / size^2))
MASS::boxcox(lm(aphid ~ day, data = read.csv("csv/aphids.csv")))

B.12 Practical 12: Orthogonal polynomial fitting and optimum dose (Chapter 13)

nd <- read.csv("csv/ndose.csv"); nd$Nf <- factor(nd$N)
contrasts(nd$Nf) <- contr.poly(6)
summary(aov(yield ~ Nf, data = nd), split = list(Nf = list(L = 1, Q = 2, C = 3, Rest = 4:5)))
q <- lm(yield ~ N + I(N^2), data = nd); b <- coef(q)
c(physical = -b[[2]] / (2 * b[[3]]), economic = (13 / 23000 - b[[2]]) / (2 * b[[3]]))

B.13 Practical 13: Dummy variables (Chapter 14)

vg <- read.csv("csv/variety.csv")
anova(lm(yield ~ N + variety, data = vg), lm(yield ~ N * variety, data = vg))

B.14 Practical 14: Stepwise regression and selection of variables (Chapter 15)

pd   <- read.csv("csv/paddy.csv")
full <- lm(yield ~ N + P + K + OC + rain + Zn, data = pd)
step(lm(yield ~ 1, data = pd), scope = formula(full), direction = "forward")
step(full, direction = "backward")
step(lm(yield ~ 1, data = pd), scope = formula(full), direction = "both")

Questions. (a) Carry out forward selection using partial \(F\) with \(F_{IN}=4\) (use add1(..., test = "F")). (b) Compute \(C_p\) for all subsets of size 3 and 4.

B.15 Practical 15: Least median of squares (Chapter 16)

sl <- read.csv("csv/salinity.csv"); set.seed(1)
rbind(OLS = coef(lm(germ ~ EC, data = sl)),
      LMS = coef(MASS::lqs(germ ~ EC, data = sl, method = "lms")))

B.16 Practical 16: Fitting quadratic, exponential, power and growth curves (Chapter 17)

lf <- read.csv("csv/leaf.csv");   coef(lm(log(area) ~ log(length), data = lf))
aph <- read.csv("csv/aphids.csv"); coef(lm(log(aphid) ~ day, data = aph))
gr <- read.csv("csv/growth.csv")
summary(nls(drymatter ~ SSlogis(das, Asym, xmid, scal), data = gr))
summary(nls(drymatter ~ SSgompertz(das, Asym, b2, b3), data = gr))

Questions. (a) Fit the exponential and power curves by solving the normal equations by hand. (b) Compute the compound growth rate of aphid population. (c) Compare logistic and Gompertz fits.