R/lm_anova.R

Defines functions lm_anova

Documented in lm_anova

#'lm_anova
#'
#'Compute analysis of variance (or deviance) tables for fitted model objects.'
#'@param object  a result of lm_fit; only support cases when the input response variable is a vector or a n * 1 matrix and the method for fitting the model is "qr".
#'
#'@return
#' lm_anova returns a list containing following response values.
#' \item{Df}{degree of freedoms of SSR(the residual sum of squares) and SSE(sum of squared estimate of errors).}
#' \item{`Sum Sq`}{SSR and SSE.}
#' \item{`Mean Sq`}{MSR and MSE.}
#' \item{`F value`}{the F statistics.}
#' \item{`Pr(>F)`}{the p value of the f test.}
#'
#'@examples
#'n = 10; p = 5; q = 2;
#'x = matrix(rnorm(n * p), n, p) # no intercept
#'y1 = rnorm(n)
#'y2 = matrix(rnorm(n * q), n, q)
#'
#'z1 = lm_fit(x = x, y = y1)
#'z2 = lm_fit(x = x, y = y2)
#'
#'z_anova = lm_summary(z1)
#'# lm_anova function doesn't support cases lm_anova(z2)
#'# because the response value y2 is a matrix with more than 1 columns.
#'
#'@export
#'

lm_anova <- function(object){
  z = object
  coef = z$coefficients
  ans = NULL
  df.r = z$df.residual
  r = z$residuals
  f = z$fitted.values

  if (!is.null(nrow(coef))){
    stop("only support cases when the input response variable is a vector or a n * 1 matrix")
  }
  if (z$method != "qr"){
    stop("only support 'qr' method")
  }

  SSE = sum(r^2)
  SSR = ifelse(z$add.intercept, sum((f - mean(f))^2), sum(f^2))
  MSE = SSE/df.r
  MSR = SSR/(z$rank - z$add.intercept)
  f.value = SSR/(z$rank - z$add.intercept)/MSE
  numdf = z$rank - z$add.intercept
  dendf = df.r

  ans$Df = c(numdf,dendf)
  ans$`Sum Sq` = c(SSR, SSE)
  ans$`Mean Sq` = c(MSR, MSE)
  ans$`F value` = c(f.value)
  ans$`Pr(>F)` = c(pf(f.value, numdf, dendf, lower.tail = FALSE))

  ans
}
leyaozh/lm.hw4 documentation built on Dec. 3, 2019, 7:18 a.m.