# NBA guard data

nba <- read.csv(file = "c:\\data\\stat705\\NBAguards.csv")
head(nba)
tail(nba)

################################################################################
# Age model

  plot(x = nba$age, y = nba$PPM, col = "red", xlab = "Age", ylab = "PPM",
     panel.first = grid(col = "gray", lty = "dotted"))

  mod.fit1 <- lm(formula = PPM ~ age +I(age^2), data = nba)
  summary(mod.fit1)

  curve(expr = predict(object = mod.fit1, newdata = data.frame(age = x)), col = "blue",
      add = TRUE)

  save.pred <- predict(object = mod.fit1, newdata = data.frame(age = c(22, 27)))
  save.pred[2] - save.pred[1]

  library(package = emmeans)
  calc.est <- emmeans(object = mod.fit1, specs = ~ age,
    at = list(age = c(27, 22)))
  calc.est
  test.info <- contrast(object = calc.est, method = "pairwise", adjust = "none")
  test.info
  ci.info <- confint(object = test.info, adjust = "none", level = 0.95)
  ci.info

  # Cubic spline
  library(package = splines)
  mod.fit.bs <- lm(formula = PPM ~ bs(x = age, degree = 4), data = nba)
  summary(mod.fit.bs)
  curve(expr = predict(object = mod.fit.bs, newdata = data.frame(age = x),
    type = "response"), lty = 3, lwd = 2, add = TRUE)
  legend(x = 32, y = 0.8, legend = c("Quadratic", "Cubic spline"), lty = c(1,3),
         lwd = c(1,2), col = c("blue", "black"), bty = "n")


################################################################################
# Age and MPG model

  library(package = rgl)
  plot3d(x = nba$MPG, y = nba$age, z = nba$PPM, col = "blue",
         xlab = "MPG", ylab = "Age", zlab = "PPM", size = 10)
  grid3d(side = c("x", "y", "z"), col = "lightgray")

  mod.fit2 <- lm(formula = PPM ~ age + MPG + age:MPG + I(age^2) + I(MPG^2), data = nba)
  summary(mod.fit2)

  #####################
  # 3D plot

  # Obtain range for age and MPG
  range(nba$age)
  range(nba$MPG)

  # Create a grid of values for predict()
  age <- min(nba$age):max(nba$age)
  MPG <- 5:40
  pred.set <- expand.grid(age = age, MPG = MPG)
  head(pred.set)
  tail(pred.set)

  # Estimate PPM
  PPM.hat <- predict(object = mod.fit2, newdata = pred.set)
  plot.set <- data.frame(pred.set, PPM.hat)
  head(plot.set)

  # Create z-axis values - age is the columns and MPG is rows
  PPMhat.mat <- matrix(data = PPM.hat, nrow = length(MPG), ncol = length(age),
                       byrow = TRUE)
  PPMhat.mat[1:5, 1:5]

  # Plot
  persp3d(x = MPG, y = age, z = PPMhat.mat,  zlab = "PPM", col = "red", size = 1)
  # Check to make sure got x and y correct - notice that PPMhat matches plot
  #   for this age and MPG
  predict(object = mod.fit2, newdata = data.frame(age = 37, MPG = 40))

  # Add observed data values
  plot3d(x = nba$MPG, y = nba$age, z = nba$PPM, col = "blue",
         size = 10, add = TRUE)
  grid3d(side = c("x", "y", "z"), col = "lightgray")


################################################################################
# The code below was originally in the NBAguardsDiag.R program

  mod.fit <- lm(formula = PPM ~ MPG + height + FGP + age, data = nba)
  summary(mod.fit)

  ##############################################################################
  # Studentized residuals

    r.i <- rstandard(model = mod.fit)
    r.i[1:5]
    r.i[abs(r.i) > qt(p = 1-0.01/2, df = mod.fit$df.residual)]

    #Critical values
    n <- length(mod.fit$fitted.values)
    qt(p = 1-0.01/2, df = mod.fit$df.residual)
    qt(p = 1-0.05/(2*n), df = mod.fit$df.residual)

    #r.i vs. Yhat.i
    plot(x = mod.fit$fitted.values, y = r.i, xlab = "Estimated response",
      ylab = "Studentized residuals", main = expression(paste(r[i], " vs. estimated response")),
      panel.first = grid(col = "gray", lty = "dotted"),
      ylim = c(min(qt(p = 0.05/(2*n), df = mod.fit$df.residual), min(r.i)),
               max(qt(p = 1-0.05/(2*n), df = mod.fit$df.residual), max(r.i))))
    abline(h = 0, col = "darkgreen")
    abline(h = c(qt(p = 0.01/2, df = mod.fit$df.residual), qt(p = 1-0.01/2, df =
           mod.fit$df.residual)), col = "red", lwd = 2)
    abline(h = c(qt(p = 0.05/(2*n), df = mod.fit$df.residual),qt(p = 1-0.05/(2*n), df =
         mod.fit$df.residual)), col = "darkred", lwd = 2)
    identify(x = mod.fit$fitted.values, y = r.i)

    nba[c(37, 52, 53, 72),]

    # r1 - matches r.i[1]
    Y <- nba$PPM[1]
    Yhat <- mod.fit$fitted.values[1]
    X <- model.matrix(mod.fit)
    sum.fit <- summary(mod.fit)
    sigmahat.ep <- sum.fit$sigma
    H <- X %*% solve(t(X)%*%X) %*% t(X)
    (Y - Yhat)/(sigmahat.ep * sqrt(1 - H[1,1]))


  ##############################################################################
  # Studentized deleted residuals

    t.i <- rstudent(model = mod.fit)
    t.i[1:5]
    t.i[abs(t.i) > qt(p=1-0.01/2, df=mod.fit$df.residual-1)]

    # Critical values
    n <- length(mod.fit$fitted.values)
    qt(p = 1-0.01/2, df = mod.fit$df.residual-1)
    qt(p = 1-0.05/(2*n), df = mod.fit$df.residual-1)


    # t.i vs. Yhat.i
    plot(x = mod.fit$fitted.values, y = t.i, xlab = "Estimated response",
      ylab = "Studentized deleted residuals", main = expression(paste(t[i], " vs. estimated response")),
      panel.first = grid(col = "gray", lty = "dotted"),
      ylim = c(min(qt(p = 0.01/2, df = mod.fit$df.residual-1), min(t.i)),
               max(qt(p = 1-0.01/2, df = mod.fit$df.residual-1), max(t.i))))
      abline(h = 0, col = "darkgreen")
      abline(h = c(qt(p = 0.01/2, df = mod.fit$df.residual-1), qt(p = 1-0.01/2, df =
             mod.fit$df.residual-1)), col = "red", lwd = 2)
      abline(h = c(qt(p = 0.05/(2*n), df = mod.fit$df.residual-1),qt(p = 1-0.05/(2*n), df =
             mod.fit$df.residual-1)), col = "darkred", lwd = 2)
      identify(x = mod.fit$fitted.values, y = t.i)


################################################################################
# Variable (model) selection

  head(nba)

  mod.fit.all <- lm(formula = PPM ~ MPG + height + FTP + FGP + age, data = nba, na.action = "na.fail")
  summary(mod.fit.all)

  # All-subsets
  library(MuMIn)
  options(width = 60)
  allsub.aic <- dredge(global.model = mod.fit.all, rank = "AIC")
  allsub.aic[allsub.aic$delta < 5,]
  mod.fit.FTPwo <- lm(formula = PPM ~ MPG + height +   + FGP + age, data = nba, na.action = "na.fail")
  # summary(mod.fit.FTPwo)
  AIC(mod.fit.FTPwo)

  allsub.bic <- dredge(global.model = mod.fit.all, rank = "BIC")
  allsub.bic[allsub.aic$delta < 5,]


  # Stepwise
  empty.mod <- lm(formula = PPM ~ 1, data = nba)
  full.mod <- lm(formula = PPM ~ MPG + height + FTP + FGP + age, data = nba)
  forw.sel.AIC <- step(object = empty.mod, scope = list(upper = full.mod), direction = "forward",
                   k = log(2), trace = TRUE)
  forw.sel.BIC <- step(object = empty.mod, scope = list(upper = full.mod), direction = "forward",
                   k = log(nrow(nba)), trace = TRUE)

  back.sel.AIC <- step(object = full.mod, scope = list(upper = empty.mod), direction = "backward",
                   k = log(2), trace = TRUE)
  back.sel.BIC <- step(object = full.mod, scope = list(upper = empty.mod), direction = "backward",
                   k = log(nrow(nba)), trace = TRUE)

  alt.sel.AIC <- step(object = empty.mod, scope = list(upper = full.mod), direction = "both",
                   k = log(2), trace = TRUE)
  alt.sel.BIC <- step(object = empty.mod, scope = list(upper = full.mod), direction = "both",
                   k = log(nrow(nba)), trace = TRUE)


################################################################################
# Other variable selection functions

  # Another variable selection function
  library(leaps)
  select.var <- regsubsets(x = PPM ~ MPG + height + FTP + FGP + age, data = nba,
                           method = "exhaustive", nbest = 4)
  select.sum <- summary(select.var, matrix.logical = TRUE)
  select.sum

  # Adjusted R^2
  library(car)
  subsets(object = select.var, statistic = "adjr2", legend = FALSE, cex.subsets = 0.75)
  # BIC
  subsets(object = select.var, statistic = "bic", legend = FALSE, cex.subsets = 0.75)


################################################################################
# Including interaction and quadratic terms

  ##########################
  # Interactions with dredge()

  # This assumes that all two-way interactions here make sense!
  mod.fit.all.inter <- lm(formula = PPM ~ (MPG + height + FTP + FGP + age)^2, data = nba,
                          na.action = "na.fail")
  summary(mod.fit.all.inter)
  allsub.aic2 <- dredge(global.model = mod.fit.all.inter, rank = "AIC")
  allsub.aic2[allsub.aic2$delta < 2,]

  # Suppose only one interaction makes sense
  mod.fit.one.inter <- lm(formula = PPM ~ MPG + height + FTP + FGP + age + FTP:FGP, data = nba,
                          na.action = "na.fail")
  summary(mod.fit.one.inter)
  allsub.aic3 <- dredge(global.model = mod.fit.one.inter, rank = "AIC")
  allsub.aic3[allsub.aic2$delta < 2,]
  # Notice that the main effects for FTP and FGP are included if the interaction is included

  # Suppose only height^2 makes sense for a quadratic term
  mod.fit.one.quad <- lm(formula = PPM ~ MPG + height + FTP + FGP + age + I(height^2), data = nba,
                          na.action = "na.fail")
  summary(mod.fit.one.quad)
  allsub.aic4 <- dredge(global.model = mod.fit.one.quad, rank = "AIC")
  allsub.aic4[allsub.aic2$delta < 2,]
  # Notice that the main effect for height is NOT always included with height^2
  #   Therefore, dredge() should not be used here for this type of model term


  ##########################
  # Interactions with step()

  # Interactions using ( )^2
  empty.mod <- lm(formula = PPM ~ 1, data = nba)
  full.mod <- lm(formula = PPM ~ (MPG + height + FTP + FGP + age)^2, data = nba)
  forw.sel.AIC <- step(object = empty.mod, scope = list(upper = full.mod), direction = "forward",
                   k = log(2), trace = TRUE)

  # Simple interactions like MPG:age
  empty.mod <- lm(formula = PPM ~ 1, data = nba)
  full.mod <- lm(formula = PPM ~ MPG + height + FTP + FGP + age + MPG:age, data = nba)
  forw.sel.AIC <- step(object = empty.mod, scope = list(upper = full.mod), direction = "forward",
                   k = log(2), trace = TRUE)

  # Suppose only MPG^2 makes sense for a quadratic term
  empty.mod <- lm(formula = PPM ~ 1, data = nba)
  full.mod <- lm(formula = PPM ~ MPG + height + FTP + FGP + age + I(MPG^2), data = nba)
  forw.sel.AIC <- step(object = empty.mod, scope = list(upper = full.mod), direction = "forward",
                   k = log(2), trace = TRUE)
  # Notice that the main effect for MPG is NOT always included with MPG^2
  #   Therefore, step() should not be used here for this type of model term













#