R/dtukey.R

Defines functions dtukey

Documented in dtukey

#' Density of the Studentized Range Distribution
#'
#' @param q Vector of quantiles.
#' @param nmeans Number of means (groups) being compared. Greater than 1. Internally coerced to integer.
#' @param df Degrees of freedom for s (Error). Should be equal to or greater than 2.
#' @param nranges Number of independent ranges (for simultaneous coverage).
#' Should be equal to or greater than 1. Default is 1. Internally coerced to integer.
#'
#' @return Density of the studentized range distribution.
#'
#' @references Copenhaver, M.D., & Holland, B. (1988).
#' Computation of the distribution of the maximum studentized range statistic
#' with application to multiple significance testing of simple effects.
#' *Journal of Statistical Computation and Simulation*, *30*(1), 1–15.
#'
#' @export
#'
#' @examples dtukey(1, 3, 196)
dtukey <- function(q, nmeans, df, nranges = 1L) {
  stopifnot(
    is.numeric(q), length(q) > 0L, all(is.finite(q)),
    is.numeric(nmeans), length(nmeans) == 1L, is.finite(nmeans),
    nmeans > 1,
    is.numeric(df), length(df) == 1L, is.finite(df), df > 0,
    is.numeric(nranges), length(nranges) == 1L, is.finite(nranges),
    nranges >= 1
  )

  nmeans <- as.integer(nmeans)
  nranges <- as.integer(nranges)

  vapply(as.numeric(q), function(qi) {
    if (qi < 0) return(0)

    env <- list2env(list(
      x = qi, nmeans = nmeans, df = df, nranges = nranges
    ))

    d <- function(central = TRUE, dir = 1, lower.tail = TRUE) {
      g <- stats::numericDeriv(
        bquote(stats::ptukey(x, nmeans = nmeans, df = df, nranges = nranges, lower.tail = .(lower.tail))),
        theta = "x", rho = env,
        central = central, dir = dir
      )
      as.numeric(attr(g, "gradient"))
    }

    if (qi == 0) {
      d(central = FALSE, dir = 1, lower.tail = TRUE)
    } else if (stats::ptukey(qi, nmeans = nmeans, df = df, nranges = nranges, lower.tail = TRUE) <= 0.5) {
      d(central = TRUE, lower.tail = TRUE)
    } else {
      -d(central = TRUE, lower.tail = FALSE)
    }
  }, numeric(1))
}

Try the Keng package in your browser

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

Keng documentation built on Nov. 28, 2026, 9:06 a.m.