R/apa_function.R

Defines functions apa

Documented in apa

#' apa
#'
#' This function takes a hypothesis test object (e.g.; t.test(), cor.test(), chisq.test()) as an input, and returns a string with the test result in APA format.
#'
#' @param test.object A hypothesis test object generated by functions such as t.test(), cor.test, chisq.test()
#' @param sig.digits The number of digits results are rounded to
#' @param tails The number of tails in the test (1 or 2)
#' @param p.lb The lower bound of the p-value display. If the p-value is less than p.lb, the exact value will not be displayed.
#' @keywords apa
#' @export
#' @examples
#'
#' x <- rnorm(100)
#' y <- x + rnorm(100)
#' a <- sample(1:3, size = 200, prob = c(.3, .2, .5), replace = TRUE)
#' b <- sample(1:3, size = 200, prob = c(.3, .2, .5), replace = TRUE)
#'
#' apa(t.test(x, y))
#' apa(cor.test(x, y))
#' apa(chisq.test(table(a, b)))
#'
apa <- function(test.object, tails = 2, sig.digits = 2, p.lb = .01) {
  statistic.id <- substr(names(test.object$statistic), start = 1, stop = 1)
  p.value <- test.object$p.value

  if (tails == 1) {
    p.value <- p.value / 2
  }

  if (p.value < p.lb) {
    p.display <- paste("p < ", p.lb, " (", tails, "-tailed)", sep = "")
  }
  if (p.value > p.lb) {
    p.display <- paste("p = ", round(p.value, sig.digits), " (", tails, "-tailed)", sep = "")
  }


  add.par <- ""

  if (grepl("product-moment", test.object$method)) {
    estimate.display <- paste("r = ", round(test.object$estimate, sig.digits), ", ", sep = "")
  }

  if (grepl("Chi", test.object$method)) {
    estimate.display <- ""

    add.par <- paste(", N = ", sum(test.object$observed), sep = "")
  }

  if (grepl("One Sample t-test", test.object$method)) {
    estimate.display <- paste("mean = ", round(test.object$estimate, sig.digits), ", ", sep = "")
  }

  if (grepl("Two Sample t-test", test.object$method)) {
    estimate.display <- paste("mean difference = ", round(test.object$estimate[2] - test.object$estimate[1], sig.digits), ", ", sep = "")
  }




  return(paste(
    estimate.display,
    statistic.id,
    "(",
    round(test.object$parameter, sig.digits),
    add.par,
    ") = ",
    round(test.object$statistic, sig.digits),
    ", ",
    p.display,
    sep = ""
  ))
}

Try the yarrr package in your browser

Any scripts or data that you put into this service are public.

yarrr documentation built on Aug. 8, 2025, 7:23 p.m.