R/diagnosis.R

Defines functions diagnosis

Documented in diagnosis

#'diagnosis
#'
#'Diagnose residuals and make plots of a linear model produced from lm1()
#'@param model input a linear model produced from lm1()
#'
#'@return different types residuals of the model: residuals, standardized residuals and studentized residuals. Also print residual plot, qqplot, scale-location plot and standardized residuals vs leverage plot.
#'
#'@examples
#'
#'model <- lm1(mpg ~ disp + wt, data = mtcars)
#'diagnosis(model)
#'
#'
#'@export
#'
diagnosis = function(model) {
  fitted.values <- model$fitted.values
  leverage <- model$leverage

  # different types of residuals: residuals, standardized residuals, studentized residuals
  res <- model$res
  std.res <- res/sqrt(model$MSE)
  stud.res <- res/sqrt(model$MSE*(leverage))
  residuals <- data.frame(residuals = res, standard_residuals = std.res, studentized_residuals = stud.res)

  # plots
  opar <- par(mfrow = c(2,2))
  par(mar=c(2,2,2,2))
  # residual plot
  plot(fitted.values,res, main = "Residuals vs Fitted", ylab = "residuals")
  abline(h=0, col = "red")
  # qqplot for normality
  qqnorm(std.res, main = "Normal Q-Q", ylab = "standard_residuals")
  abline(a=0, b=1, col = "red")
  # scale-location
  plot(fitted.values,sqrt(abs(std.res)), main = "Scale-Location", ylab = "sqrt(|standard_residuals|)")
  # std.res vs leverage
  plot(leverage,std.res, main = "Residuals vs Leverage", ylab = "standard_residuals")
  par(opar)

  return(residuals) }
mengqi00/linear1 documentation built on Dec. 21, 2021, 4:57 p.m.