R/apa.regression.lmerModLmerTest.r

#' @title apa.regression.lmerModLmerTest
#'
#' @description APA formated interpretation of \code{\link[lmerTest]{lmer}}
#'
#' @export
#' 
#' @param model \code{\link[lmerTest]{lmer}} 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
#'   Pulls out the fixed effects, confidence interval, statistic, and p-value of the model; formats the fixed effects, confidence interval, and p-values; calculates \eqn{r = \sqrt{t^2/(t^2+df)}}; and produces a table.
#'
#' @examples
#'   \dontshow{
#'     library(apaformat)
#'     library(lmerTest)
#'     library(knitr)}
#'   x = testdata.apa.regression.lmerModLmerTest
#'   model = lmer(Response ~ Treatment + (1|FocusGroup), data = x)
#'   ci = confint(model, parm = "beta_")
#'   tab = apa.regression(model, ci)
#'   kable(tab, caption = 'Regression coefficients with 95% CI', booktabs = TRUE)
#'   
apa.regression.lmerModLmerTest = function(model, ci = NULL) {

  stopifnot(class(model) == "lmerModLmerTest")

  fe = lme4::fixef(model)  
  cf = stats::coef(summary(model))[,3:5]
  
  fe = round(fe, 3)
  cif = NULL
  if(!is.null(ci)) { cif = apa.confint(ci) }
  t = apa.tstat(cf[,2], cf[,1])
  r = sprintf("(r = %.3f)", round(sqrt(cf[,2]^2/(cf[,2]^2 + cf[,1])), 3))       
  pv = apa.pvalue(cf[,3])

  tab = cbind(fe, cif, t, r, pv)
  colnames(tab) = c("Fixed Effects", if(!is.null(cif)) { colnames(cif) }, "t-test", "r", "p-value")

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