R/apa.regression.glm.r

#' @title apa.regression.glm
#'
#' @description APA formated interpretation of \code{\link[stats]{glm}}
#'
#' @export
#' 
#' @param model \code{\link[stats]{glm}} to be formatted
#' @param ci \code{\link[stats]{confint}} or similar (optional)
#' @return the formatted \code{\link[base]{data.frame}}
#'
#' @author Mark Newman, \email{mark@trinetteandmark.com}
#' @keywords regression 
#' @family regression
#' 
#' @details
#'   Currently only the binomial family is supported \cr \cr
#'   Pulls out the log odds, confidence interval, statistic, and p-value of the model; converts the log odds and confidence interval to odds ratios; formats p-values; and produces a table.
#'
#' @examples
#'   \dontshow{
#'     library(apaformat)
#'     library(knitr)}
#'   x = testdata.apa.regression.glm
#'   model = glm(Response ~ Attribute, data = x, family = binomial())
#'   ci = confint(model)
#'   tab = apa.regression(model, ci)
#'   kable(tab, caption = 'Odds ratios with 95% CI', booktabs = TRUE)
#'   
apa.regression.glm = function(model, ci = NULL) {

  stopifnot(all(class(model) == c("glm", "lm")))
  stopifnot(model$family$family == "binomial")

  cf = stats::coef(summary(model))
  
  or = round(exp(cf[,1]), 3)
  cif = NULL
  if(!is.null(ci)) { cif = apa.confint(exp(ci)) }
  z = apa.zstat(cf[,3])
  pv = apa.pvalue(cf[,4])

  tab = cbind(or, cif, z, pv)
  colnames(tab) = c("Odds Ratio", if(!is.null(cif)) { colnames(cif) }, "z score", "p-value")

  return(tab)
}
markanewman/apaformat documentation built on May 10, 2019, 1:19 a.m.