R/normal_Tests.R

Defines functions .rita_test_info .rita_chisq_cells chisqTest .rita_jb_components JBTest .rita_dp_kurtosis_z DPTest .rita_ad_pvalue ADTest .rita_count .rita_exact_choice .rita_sw_test SWTest .rita_molin_abdi_p .rita_lilliefors_null .rita_lilliefors_d KSLTest

Documented in ADTest chisqTest DPTest JBTest KSLTest SWTest

###################################################################################
#' Kolmogorov-Smirnov-Lilliefors Test
#'
#' This function computes the Lilliefors variant of the one-sample Kolmogorov-Smirnov test.
#'
#' @details The default method = "molin-abdi" uses the polynomial approximation of Molin
#' and Abdi (1998).
#'
#' The alternative method = "monte-carlo" replaces the polynomial approximation
#' with simulation-based calibration. Each of n_sim independent standard-normal
#' samples has the same usable sample size as the observed data. The mean and
#' sample standard deviation are re-estimated for each simulated sample before
#' calculating the Lilliefors statistic (D). The upper-tail p-value is
#' calculated as (1 + count(D_sim >= D_obs)) / (n_sim + 1), counting simulated
#' statistics equal to or greater than the observed statistic as exceedances.
#' This procedure simulates the normal null distribution rather than resampling
#' the observed data. Use set.seed() before calling the function for
#' reproducibility; simulation advances R's random-number generator state.
#'
#' At least four finite, nonconstant observations are required after omitting NA
#' and NaN. Input must be a numeric vector. Centered and scaled calculations
#' improve numerical stability, provided the relevant differences remain
#' representable. Ties are accepted when calculating the statistic, but
#' continuous-normal calibration is not established for rounded or discretized
#' observations.
#'
#' Monte Carlo p-values are returned without rounding to prevent small positive
#' estimates from being displayed as zero. The statistic (D) retains
#' three-decimal rounding, and significance decisions use the unrounded p-value
#' with the strict threshold alpha/j. The minimum attainable Monte Carlo p-value
#' is 1 / (n_sim + 1), reflecting simulation resolution rather than a lower
#' bound on the true probability.
#'
#' The monte_carlo attribute records the usable sample size, simulation count,
#' exceedances, unrounded statistic, minimum attainable p-value, presence of
#' ties, and a 95\% exact Clopper-Pearson binomial confidence interval for the
#' underlying null-tail probability conditional on the observed statistic. This
#' interval quantifies simulation uncertainty, not robustness to model
#' misspecification. Stringent significance thresholds may require substantially
#' more simulations. The default Molin–Abdi method uses three-decimal rounding.
#'
#' @param data The data of a univariate distribution for which the test statistic is computed (vector)
#' @param alpha The two-sided decision threshold used for hypothesis-testing (scalar)
#' @param j The # hypotheses tested; used to compute a Bonferonni correction, if applicable;
#'          should remain at its default if multiple testing is not an issue (scalar)
#' @param warn Logical; warn by default that clipped polynomial output is an approximation-boundary result, not a literal tail probability of zero or one.
#' @param method Exact calibration name: "molin-abdi" (default) or "monte-carlo".
#' @param n_sim Positive integer simulation count, used only for "monte-carlo";
#'              default 100000.
#'
#' @section Precision metadata:
#' Successful computed results also carry a rita_test attribute with the
#' unrounded statistic and p.value, n_tested, precision, calibration and
#' details. It records existing computations without rerunning the test.
#' Unsupported or undefined results retain their existing sentinel/NA
#' representation and may lack this attribute. See rita_analysis for reporting
#' conventions.
#'
#' @return An object including the test statistic, p-value, and a significance flag (list)
#' @export
#'
#' @references Lilliefors, H.W. (1967). On the Kolmogorov-Smirnov Test for Normality with Mean and Variance Unknown. Journal of the American Statistical Association, 62, 399-402.
#'
#'             Molin, P., & Abdi, H. (1998). New Tables and numerical approximation for the KolmogorovSmirnov/Lillierfors/Van Soest test of normality.
#'
#' @examples
#' values <- rnorm(100)
#' x <- KSLTest(data = values)
#' set.seed(2026)
#' mc <- KSLTest(values, method = "monte-carlo", n_sim = 999)
#' attr(mc, "monte_carlo") # Increase n_sim for precise tail inference.
KSLTest <- function(data, alpha = .05, j = 1, warn = T,
                    method = "molin-abdi", n_sim = 100000) {
  method <- .rita_exact_choice(method,c("molin-abdi","monte-carlo"),"method")
  if (method == "monte-carlo")
    n_sim <- .rita_count(n_sim,1,.Machine$integer.max,"n_sim")
  if (!is.numeric(data) || !is.null(dim(data)))
    stop("KSLTest requires a numeric vector.",call. = FALSE)
  data <- data[!is.na(data)]
  N <- length(data)
  if (N < 4 || any(!is.finite(data)))
    stop("KSLTest requires at least four finite observations after omitting missing values.",
         call. = FALSE)
  d <- .rita_lilliefors_d(data)
  if (method == "monte-carlo") {
    null_d <- .rita_lilliefors_null(N,n_sim)
    exceedances <- sum(null_d >= d)
    p <- (1 + exceedances) / (n_sim + 1)
    result <- list(c(D = round(d,3)),c(`P-value` = p),c(Sig. = p < alpha / j))
    attr(result,"monte_carlo") <- list(method=method,n=N,n_sim=n_sim,
      statistic=d,exceedances=exceedances,min_p=1/(n_sim+1),
      conf.int=unname(stats::binom.test(exceedances,n_sim)$conf.int),
      conf.level=.95,ties=anyDuplicated(data)>0L)
    return(.rita_test_info(result,d,p,N,"normal-null-monte-carlo"))
  }
  AProb <- .rita_molin_abdi_p(d,N)
  raw_probability <- AProb
  # Preserve the documented legacy approximation/clipping in the default method.
  if (AProb < 0) {
    if (warn) warning("KSLTest: Molin-Abdi returned a negative approximation; clipped to 0. This is an approximation-boundary result, not a literal tail probability of zero. Use method = 'monte-carlo' for simulation calibration.",call.=FALSE)
    AProb <- 0
  } else if (AProb > 1) {
    if (warn) warning("KSLTest: Molin-Abdi returned an approximation above 1; clipped to 1. This is an approximation-boundary result, not a literal tail probability of one. Use method = 'monte-carlo' for simulation calibration.",call.=FALSE)
    AProb <- 1
  }
  result <- list(c(D=round(d,3)),c(`P-value`=round(AProb,3)),c(Sig.=AProb < alpha / j))
  .rita_test_info(result,d,AProb,N,"molin-abdi",
    list(raw_probability=raw_probability,clipped=raw_probability < 0 || raw_probability > 1))
}

# Recenter before scaling: the safe midpoint avoids overflow in subtraction;
# normalization before sd avoids squared-magnitude overflow and underflow.
.rita_lilliefors_d <- function(x) {
  limits <- range(x)
  center <- limits[1]/2 + limits[2]/2
  y <- x - center
  spread <- max(abs(y))
  if (!is.finite(spread) || spread <= 0)
    stop("KSLTest requires nonconstant observations with positive variance.",call.=FALSE)
  y <- y / spread
  s <- sd(y)
  if (!is.finite(s) || s <= 0)
    stop("KSLTest requires a finite, positive standardized sample variance.",call.=FALSE)
  p <- pnorm(sort((y-mean(y))/s))
  n <- length(x)
  i <- seq_len(n)
  max(i/n-p,p-(i-1)/n)
}

.rita_lilliefors_null <- function(n,n_sim) {
  vapply(seq_len(n_sim),function(i) .rita_lilliefors_d(stats::rnorm(n)),numeric(1))
}

.rita_molin_abdi_p <- function(d,n) {
  # Rationalize the positive quadratic root to avoid subtraction cancellation.
  b <- 1.30748185078790 + n
  q <- (1/d)^2 - 0.37872256037043
  A <- 2*q / (b + sqrt(b^2 + 4*0.08861783849346*q))
  -0.37782822932809 + 1.67819837908004*A - 3.02959249450445*A^2 +
    2.80015798142101*A^3 - 1.39874347510845*A^4 + 0.40466213484419*A^5 -
    0.06353440854207*A^6 + 0.00287462087623*A^7 + 0.00069650013110*A^8 -
    0.00011872227037*A^9 + 0.00000575586834*A^10
}
###################################################################################
#' Shapiro-Wilk Test
#'
#' This function is a wrapper for shapiro.test() from the stats package. Options
#' added include an ability to toggle a Bonferonni correction for significance, a
#' corresponding significance flag, and reorganized output to facilitate integration
#' with the Rita package.
#'
#' @details With 3 to 5000 usable observations, the ordinary stats::shapiro.test is
#' performed. When ‘data’ has N > 5000 and subsample_n = 5000 (default), a
#' sample of size N = 5000 is constructed by taking a random subsample without
#' replacement from ‘data’ to approximate a Shapiro-Wilk p-value. Select large_n
#' = "error" to terminate instead of sampling. With fewer than three usable
#' observations, testing is terminated without computed results. NA/NaN are
#' omitted before checking sample size.
#'
#' Subsampling advances R’s RNG without resetting it; use set.seed() before
#' calling. Existing ties in the data are not removed. The sampling attribute
#' records original, usable and analyzed sizes, original-input indices, and a
#' random-subsample method label, even when warn=FALSE. Rita’s sw_large_n option
#' shares one set across selected transformations in a call. Significance uses
#' the unrounded p-value against alpha/j; displayed values retain three-decimal
#' rounding.
#'
#' @param data Data of a univariate distribution for which the test statistic is computed
#'             (vector)
#' @param alpha The two-sided decision threshold used for hypothesis-testing
#' @param j The # hypotheses tested; used to compute a Bonferonni correction, if applicable;
#'          should remain at its default if multiple testing is not an issue (scalar)
#' @param warn Logical; emit a sample-size diagnostic for random subsampling (enabled by default)
#'             or termination below three usable observations.
#' @param large_n Exact policy for more than 5000 usable observations: "subsample"
#'                (default) or "error".
#' @param subsample_n Integer from 3 to 5000; subset size when large_n="subsample"
#'                    and usable n exceeds 5000. Default 5000.
#'
#' @section Precision metadata:
#' Successful computed results also carry a rita_test attribute with the
#' unrounded statistic and p.value, n_tested, precision, calibration and
#' details. It records existing computations without rerunning the test.
#' Unsupported or undefined results retain their existing sentinel/NA
#' representation and may lack this attribute. See rita_analysis for reporting
#' conventions.
#'
#' @return An object including the test statistic, p-value, and a significance flag (list)
#' @export
#'
#' @references Patrick Royston (1982). An extension of Shapiro and Wilk's W test for normality to large samples. Applied Statistics, 31, 115--124. 10.2307/2347973
#'
#'             Patrick Royston (1982). Algorithm AS 181: The W test for Normality. Applied Statistics, 31, 176--180. 10.2307/2347986
#'
#'             Patrick Royston (1995). Remark AS R94: A remark on Algorithm AS 181: The W test for normality. Applied Statistics, 44, 547--551. 10.2307/2986146
#'
#' @examples
#' values <- rnorm(100)
#' x <- SWTest(data = values)
#' set.seed(2026)
#' large_values <- rnorm(6000)
#' sampled <- SWTest(large_values, warn = FALSE)
#' attr(sampled, "sampling")[c("original_n", "analyzed_n")]
SWTest <- function(data, alpha = .05, j = 1, warn = T,
                   large_n = "subsample", subsample_n = 5000) {
  .rita_sw_test(data,alpha,j,warn,large_n,subsample_n)
}

.rita_sw_test <- function(data,alpha,j,warn,large_n,subsample_n,indices=NULL) {
  large_n <- .rita_exact_choice(large_n,c("error","subsample"),"large_n")
  subsample_n <- .rita_count(subsample_n,3,5000,"subsample_n")
  if (!is.numeric(data)) stop("SWTest requires numeric observations.",call.=FALSE)
  original_n <- length(data)
  usable <- which(!is.na(data))
  data <- data[usable]
  n <- length(data)
  if (!is.null(indices) && n != original_n)
    stop("Shared Shapiro-Wilk sampling requires the same observation rows in every transformation; transformation-specific missing values were found.",
         call.=FALSE)
  if (n < 3) {
    if (warn) warning("Note: SW Test terminated due to N < 3.")
    return(list(rep("F",3)))
  }
  if (any(!is.finite(data)))
    stop("SWTest requires finite observations after omitting missing values.",call.=FALSE)
  if (n > 5000 && large_n == "error")
    stop("SWTest supports 3 to 5000 usable observations; use large_n = 'subsample' to explicitly sample without replacement.",
         call.=FALSE)
  sampled <- n > 5000
  if (sampled) {
    if (is.null(indices)) indices <- sample.int(n,subsample_n,replace=FALSE)
    if (length(indices)!=subsample_n || anyNA(indices) || anyDuplicated(indices) ||
        any(indices<1 | indices>n | indices!=floor(indices)))
      stop("Invalid shared Shapiro-Wilk subsample indices.",call.=FALSE)
    data <- data[indices]
  }
  ref <- shapiro.test(sort(data))
  result <- list(round(ref$statistic,3),c(`P-value`=round(ref$p.value,3)),
                 c(Sig.=ref$p.value < alpha / j))
  if (sampled) {
    attr(result,"sampling") <- list(original_n=original_n,usable_n=n,
      analyzed_n=length(data),replace=FALSE,indices=usable[indices],
      method="random subsample without replacement")
    if (warn) warning(sprintf("SWTest: %d original observations (%d usable); result based on a random subsample of %d without replacement.",
                              original_n,n,length(data)),call.=FALSE)
  }
  .rita_test_info(result,unname(ref$statistic),ref$p.value,length(data),"stats-shapiro-wilk")
}

.rita_exact_choice <- function(value,choices,argument) {
  if (is.character(value) && length(value)==1L && !is.na(value) && value %in% choices)
    return(value)
  stop(sprintf("Invalid %s. Choose: %s.",argument,paste(choices,collapse=", ")),call.=FALSE)
}

.rita_count <- function(value,lower,upper,argument) {
  if (!is.numeric(value) || length(value)!=1L || is.na(value) || !is.finite(value) ||
      value!=floor(value) || value<lower || value>upper)
    stop(sprintf("%s must be an integer from %s to %s.",argument,lower,upper),call.=FALSE)
  as.integer(value)
}
###################################################################################
#' Anderson-Darling Test
#'
#' This function computes the one-sample Anderson-Darling test statistic and p-value
#' for fit to a normal distribution.
#'
#' @details An adjusted statistic provided by D’agostino & Stephens (1986) is used, where
#' the mean and variance of the population are treated as unknown. D’agostino &
#' Stephen’s (1986) text provides the equations used to obtain the function’s
#' p-values.
#'
#' The modified statistic follows Table 4.7, Case 3, and the p-value follows
#' Table 4.9. Log-CDF and log-survival probabilities are evaluated directly.
#' Standardization uses centered, scaled coordinates. Constant observations,
#' fewer than two non-missing observations, or infinite observations terminate
#' testing with an error. Missing values (NA and NaN) are omitted before
#' calculating the statistic.
#'
#' At the approximation breakpoints, 0.20 uses the first formula, 0.34 uses the
#' second, and 0.60 uses the fourth. The statistic and p-value are rounded to
#' three decimals; significance uses the unrounded p-value and alpha / j. Per
#' limitations of D’agostino & Stephen’s approximation, extrapolation to extreme
#' statistics can yield invalid p-values, including values above one; the
#' returned p-value and significance flag must not be interpreted as calibrated
#' inference in that regime.
#'
#' @param data Data of a univariate distribution for which the test statistic is computed
#'            (vector)
#' @param alpha The significance threshold for the upper-tail test
#' @param j The # hypotheses tested; used to compute a Bonferonni correction, if applicable;
#'          should remain at its default if multiple testing is not an issue (scalar)
#'
#' @section Precision metadata:
#' Successful computed results also carry a rita_test attribute with the
#' unrounded statistic and p.value, n_tested, precision, calibration and
#' details. It records existing computations without rerunning the test.
#' Unsupported or undefined results retain their existing sentinel/NA
#' representation and may lack this attribute. See rita_analysis for reporting
#' conventions.
#'
#' @return An object including the test statistic, p-value, and a significance flag (list)
#' @export
#'
#' @references D'agostino, R. B., & Stephens, M. A. (1986). Goodness-of-fit-techniques (Vol. 68). CRC press.
#'
#' @examples
#' values <- rnorm(100)
#' x <- ADTest(data = values)
ADTest <- function(data, alpha = .05, j = 1) {
  alpha <- alpha / j
  data <- sort(data)
  N <- length(data)
  if (N < 2 || any(!is.finite(data)) || data[1] == data[N])
    stop("ADTest requires at least two non-missing observations with a finite, positive sample standard deviation (nonconstant data).",
         call. = FALSE)

  z <- .rita_standardize(data)$z
  i <- seq_len(N)
  logComb <- (2 * i - 1) * pnorm(z,log.p = TRUE) +
    (2 * (N - i) + 1) * pnorm(z,lower.tail = FALSE,log.p = TRUE)
  S <- sum(logComb) / N
  AD <- ((-N) - S) * (1 + (.75 / N) + (2.25 / N^2))
  p <- .rita_ad_pvalue(AD)

  sigFL <- p < alpha
  names(sigFL) <- "Sig."
  names(AD) <- "AD"
  names(p) <- "P-value"
  stats <- list(round(AD,3),round(p,3),sigFL)

  return(.rita_test_info(stats,unname(AD),unname(p),N,"stephens-1986"))
}

# Stephens (1986), Table 4.9, A^2 Case 3. Keep the final polynomial's
# calibration unchanged until the maintainer selects an extreme-tail policy.
.rita_ad_pvalue <- function(AD) {
  if (AD <= .20) {
    -expm1(-13.436 + (101.14 * AD) - (223.73 * AD^2))
  } else if (AD <= .34) {
    -expm1(-8.318 + (42.796 * AD) - (59.938 * AD^2))
  } else if (AD < .60) {
    exp(0.9177 - (4.279 * AD) - (1.38 * AD^2))
  } else {
    exp(1.2937 - (5.709 * AD) + (0.0186 * AD^2))
  }
}
###################################################################################
#' D'agostino Pearson Omnibus Test
#'
#' This function computes the D'agostino Pearson omnibus test using adjusted Fisher-
#' Pearson skewness and kurtosis estimators.
#'
#' @details The adjusted skewness and kurtosis coefficients are computed using the sample
#' standard deviation in centered, scaled coordinates to improve numerical
#' stability. These coefficients are converted to moment ratios using equations
#' 24–25 of D'Agostino, Belanger, and D'Agostino (1990) before constructing the
#' standardized skewness and kurtosis statistics. The omnibus p-value is
#' calculated from the upper tail of a chi-square distribution with two degrees
#' of freedom.
#'
#' At least eight usable observations are required (N >= 8). However, the
#' kurtosis approximation is intended for sample sizes of at least 20.
#' Accordingly, for 8 <= N < 20, a warning is issued when warn = TRUE. The test
#' statistic and p-value are displayed to three decimal places, while
#' significance is determined using the unrounded p-value.
#'
#' The kurtosis transformation uses a signed real cube root. If the
#' transformation denominator is zero, the observations are constant, or
#' intermediate calculations produce nonfinite values, the named statistic,
#' p-value, and significance flag are returned as NA, with a warning when warn =
#' TRUE. Missing observations (NA and NaN) are omitted before determining sample
#' size. Infinite observations also produce NA results.
#'
#' @param data Data of a univariate distribution for which the test statistic is computed
#'            (vector)
#' @param alpha The significance threshold for the upper-tail omnibus test
#' @param j The # hypotheses tested; used to compute a Bonferonni correction, if applicable;
#'          should remain at its default if multiple testing is not an issue (scalar)
#' @param warn Logical; emit warnings for termination at N < 8, the kurtosis
#'             approximation at N < 20, and undefined numerical results.
#'
#' @section Precision metadata:
#' Successful computed results also carry a rita_test attribute with the
#' unrounded statistic and p.value, n_tested, precision, calibration and
#' details. It records existing computations without rerunning the test.
#' Unsupported or undefined results retain their existing sentinel/NA
#' representation and may lack this attribute. See rita_analysis for reporting
#' conventions.
#'
#' @return An object including the test statistic, p-value, and a significance flag (list)
#' @export
#'
#' @references D'agostino, R. B., & Stephens, M. A. (1986). Goodness-of-fit-techniques (Vol. 68). CRC press.
#'
#' D’Agostino, R. B., Belanger, A., & D’Agostino, R. B., Jr. (1990).
#' A Suggestion for Using Powerful and Informative Tests of Normality.
#' \emph{The American Statistician, 44}(4), 316-321.\cr
#' \url{https://doi.org/10.2307/2684359}
#'
#'             Shreve, Joni N. and Donna Dea Holland . 2018. SAS® Certification Prep
#'             Guide: Statistical Business Analysis Using SAS®9. Cary, NC: SAS Institute Inc.
#'
#' @examples
#' values <- rnorm(100)
#' x <- DPTest(data = values)
DPTest <- function(data, alpha = .05, j = 1, warn = T) {
  alpha <- alpha / j
  data <- sort(data)
  N <- length(data)
  if (N < 8) {
    if (warn)
      warning("Note: DP Test terminated due to N < 8.")
    return(list(rep("F",3)))
  }
  if (N < 20 && warn)
    warning("The D'Agostino-Pearson kurtosis approximation may be unreliable for n < 20.",
            call. = FALSE)

  undefined <- function(reason, tested_n = 0L) {
    if (warn)
      warning(paste0("DPTest could not be computed: ",reason,"."), call. = FALSE)
    result <- list(c(K = NA_real_), c(`P-value` = NA_real_), c(Sig. = NA))
    .rita_test_info(result, NA_real_, NA_real_, tested_n, "chi-square-2",
                    reason = paste0(reason, "."))
  }
  if (any(!is.finite(data)))
    return(undefined("observations must be finite"))

  if (data[1] == data[N])
    return(undefined("sample standard deviation must be finite and positive"))
  z <- .rita_standardize(data)$z
  G1 <- .rita_adjusted_skewness(z)
  G2 <- .rita_adjusted_kurtosis(z)
  # Published conversions from adjusted Fisher coefficients (1990, eqs. 24-25).
  sqrtB1 <- (N - 2) / sqrt(N * (N - 1)) * G1
  B2 <- (N - 2) * (N - 3) / ((N + 1) * (N - 1)) * G2 +
    3 * (N - 1) / (N + 1)
  if (!all(is.finite(c(G1,G2,sqrtB1,B2))))
    return(undefined("nonfinite moment estimates", N))

  # Compute the D'agostino test statistic for skew:
  c <- ( 3 * (N^2 + 27 * N -70) * (N + 1) * (N + 3) ) / ( (N - 2) * (N + 5) * (N + 7) * (N + 9) )
  wSq <- sqrt(2 * (c - 1)) - 1
  a <- sqrt((wSq - 1) / 2)
  b <- 1 / sqrt(log(sqrt(wSq)))
  mu <- a * sqrtB1 * sqrt( ((N + 1) * (N + 3)) / (6 * (N - 2)) )
  zSkew <- b * asinh(mu)

  # Compute the D'agostino test statistic for kurtosis:
  d <- sqrt( ((N + 1)^2 * (N + 3) * (N + 5)) / (24 * N * (N - 2) * (N - 3)) )
  e <- ((6 * (N^2 - 5 * N + 2)) / ((N + 7) * (N + 9))) * sqrt( (6 * (N + 3) * (N + 5)) / (N * (N - 2) * (N - 3)) )
  f <- 6 + (8 / e) * (2 / e + sqrt(1 + 4 / e^2))
  if (!all(is.finite(c(zSkew,d,e,f))) || f <= 4)
    return(undefined("nonfinite or invalid transformation parameters", N))
  g <- d * (B2 - ((3 * (N - 1)) / (N + 1)) ) * sqrt(2 / (f - 4))
  zKurt <- .rita_dp_kurtosis_z(f,g)
  if (!is.finite(zKurt))
    return(undefined("zero kurtosis denominator or nonfinite transformation result", N))

  # Compute omnibus statistic:
  K <- zSkew^2 + zKurt^2
  if (!is.finite(K))
    return(undefined("nonfinite omnibus statistic", N))

  # Compute p-value:
  p <- pchisq(K,df = 2, lower.tail = F)
  sigFL <- p < alpha
  names(sigFL) <- "Sig."
  names(K) <- "K"
  names(p) <- "P-value"
  stats <- list(round(K,3),round(p,3),sigFL)

  return(.rita_test_info(stats,unname(K),unname(p),N,"chi-square-2"))
}

# The real cube root is defined on both signs. At a zero denominator the
# transform is undefined; do not interpret an infinity as certain rejection.
.rita_dp_kurtosis_z <- function(A, g) {
  if (!all(is.finite(c(A,g))) || A <= 4)
    return(NA_real_)
  denominator <- 1 + g
  if (!is.finite(denominator) || denominator == 0)
    return(NA_real_)
  v <- (1 - 2 / A) / denominator
  r <- 2 / (9 * A)
  if (!is.finite(v) || !is.finite(r) || r <= 0)
    return(NA_real_)
  z <- (1 - r - sign(v) * abs(v)^(1/3)) / sqrt(r)
  if (is.finite(z)) z else NA_real_
}
###################################################################################
#' Jarque-Bera Test
#'
#' Tests normality using the adjusted Fisher-Pearson skewness and excess kurtosis.
#'
#' @details With n usable observations and adjusted skewness and excess kurtosis
#' coefficients (G1) and (G2), the test statistic is JB = (n / 6) (G1^2 + G2^2 /
#' 4) (Jarque & Bera, 1980). Both coefficients are calculated using the sample
#' standard deviation. Fewer than four usable observations produce a failure
#' result, with a diagnostic message printed when warn = T. Infinite
#' observations and undefined variance at supported sample sizes produce errors.
#'
#' For 4 <= n < 2000, the p-value is estimated using N_Sample independent
#' samples from the standard normal distribution. Each simulated sample is
#' standardized using its own mean and sample standard deviation before
#' calculating the statistic. The Monte Carlo upper-tail p-value is (1 +
#' exceedances) / (N_Sample + 1), with ties counted as exceedances. Use
#' set.seed() before calling the function to reproduce results under the same R
#' random-number generation configuration. Simulation advances the caller's RNG
#' state. For n >= 2000, the p-value uses an asymptotic chi-square approximation
#' with two degrees of freedom. Both approaches assume independent observations
#' from a continuous normal distribution under the null hypothesis.
#'
#' Significance is determined by comparing the unrounded p-value with the strict
#' threshold alpha / j. With the default 10,000 simulation replicates, the
#' minimum attainable Monte Carlo p-value is 1 / 10001, and the approximate
#' simulation standard error at p = 0.05 is 0.00218. More stringent significance
#' thresholds or greater precision may require additional replicates.
#'
#' @param data Numeric observations for one univariate distribution. NA and NaN are omitted
#' and numeric matrices and arrays are flattened.
#'
#' @param alpha Upper-tail significance level.
#' @param j Number of hypotheses in the Bonferroni adjustment. Default 1.
#' @param N_Sample Positive integer number of normal-null replicates for 4 <= n < 2000. Default 10000.
#' @param warn Logical controlling warnings for simulation and termination below four usable observations.
#'
#' @section Precision metadata:
#' Successful computed results also carry a rita_test attribute with the
#' unrounded statistic and p.value, n_tested, precision, calibration and
#' details. It records existing computations without rerunning the test.
#' Unsupported or undefined results retain their existing sentinel/NA
#' representation and may lack this attribute. See rita_analysis for reporting
#' conventions.
#'
#' @return A three-element list of named scalars for the statistic, p-value (both rounded to three
#' decimals), and significance flag. For a simulated result the monte_carlo
#' attribute records n, n_sim, exceedances, min_p and the unrounded p.value.
#' A displayed zero can represent a positive probability below 0.0005.
#' For n < 4 the return is list(rep("F", 3)).
#' @export
#'
#' @references Jarque, C. M. and Bera, A. K. (1980). Efficient tests for normality, homoscedasticity and serial independence of regression residuals. Economics Letters, 6(3), pp. 255-259.
#'
#' Shreve, Joni N. and Donna Dea Holland. 2018. SAS® Certification Prep Guide: Statistical Business Analysis Using SAS®9. Cary, NC: SAS Institute Inc.
#' @examples
#' set.seed(42)
#' x <- JBTest(qnorm(ppoints(40)), warn = FALSE)
#' attr(x, "monte_carlo")$p.value
JBTest <- function(data, alpha = .05, j = 1, N_Sample = 10000, warn = T) {
  if (!is.numeric(data) || is.complex(data))
    stop("JBTest requires numeric observations.", call. = FALSE)
  data <- as.vector(data)
  data <- data[!is.na(data)]
  n <- length(data)
  if (any(!is.finite(data)))
    stop("JBTest requires finite observations after omitting NA/NaN.", call. = FALSE)
  if (n < 4) {
    if (warn) warning("JBTest requires at least four usable observations.", call. = FALSE)
    return(list(rep("F", 3)))
  }

  observed <- .rita_jb_components(data)[["JB"]]
  if (n < 2000) {
    B <- .rita_count(N_Sample, 1, .Machine$integer.max, "N_Sample")
    if (warn) warning("JBTest uses normal-null Monte Carlo calibration for n < 2000.",
                      call. = FALSE)
    exceedances <- 0
    for (i in seq_len(B)) {
      simulated <- .rita_jb_components(stats::rnorm(n))[["JB"]]
      exceedances <- exceedances + (simulated >= observed)
    }
    p <- (1 + exceedances) / (1 + as.double(B))
  } else {
    p <- pchisq(observed, df = 2, lower.tail = FALSE)
  }

  result <- list(c(JB = round(observed, 3)), c(`P-value` = round(p, 3)),
                 c(Sig. = p < alpha / j))
  if (n < 2000)
    attr(result, "monte_carlo") <- list(n = n, n_sim = B, exceedances = exceedances,
                                        min_p = 1 / (1 + as.double(B)), p.value = p)
  .rita_test_info(result,observed,p,n,if (n < 2000) "normal-null-monte-carlo" else "chi-square-2")
}

# Use the sample-SD Fisher formulas on both sides of the simulated comparison.
# Recenter and rescale first so finite data with extreme units can be fitted.
.rita_jb_components <- function(x) {
  n <- as.double(length(x))
  limits <- range(x)
  centered <- x - (limits[1] / 2 + limits[2] / 2)
  spread <- max(abs(centered))
  if (spread == 0)
    stop("JBTest requires nonconstant observations with positive variance.", call. = FALSE)
  y <- centered / spread
  sample_sd <- sd(y)
  if (!is.finite(sample_sd) || sample_sd <= 0)
    stop("JBTest requires a positive finite standardized variance.", call. = FALSE)
  z <- (y - mean(y)) / sample_sd
  z2 <- z * z
  G1 <- n / ((n - 1) * (n - 2)) * sum(z2 * z)
  G2 <- n * (n + 1) / ((n - 1) * (n - 2) * (n - 3)) * sum(z2 * z2) -
    3 * (n - 1)^2 / ((n - 2) * (n - 3))
  c(G1 = G1, G2 = G2, JB = (n / 6) * (G1^2 + G2^2 / 4))
}
###################################################################################
#' Chi-Square Test
#'
#' This function computes the chi-square test for normality.
#'
#' @details The number of cells is k = ceiling(2*n^(2/5)) (Moore, 1986). Numerically
#' computed quantiles of the fitted normal distribution define equiprobable
#' cells with infinite outer endpoints and expected counts of (n / k), including
#' for empty cells. The mean and sample standard deviation are estimated from
#' all usable observations (missing values NA and NaN are omitted). Calculations
#' use centered and scaled coordinates to improve numerical stability. Cells are
#' right-closed, so observations exactly on an interior boundary are assigned to
#' the lower cell.
#'
#' At least three finite observations with positive sample variance are
#' required. Ties are permitted, although the continuous-normal reference
#' distribution does not account for rounding or discretization. Small expected
#' cell counts may further compromise the chi-square approximation; cells are
#' not merged.
#'
#' By default, df = NULL uses the conventional (k - 3) degrees-of-freedom
#' approximation, where (k) is determined after missing-value removal. An
#' explicitly supplied positive, finite df overrides the reference
#' distribution's degrees of freedom. Because the normal parameters are
#' estimated from ungrouped observations, the resulting chi-square reference is
#' approximate rather than an exact null distribution (Moore, 1986, Sections
#' 3.2.2 and 3.2.7). Significance decisions compare the unrounded upper-tail
#' p-value with alpha / j. Displayed values are rounded.
#'
#' @param data Data of a univariate distribution for which the test statistic is computed
#'            (numeric vector, or numeric matrix/array flattened to a vector)
#' @param alpha The upper-tail significance threshold used for hypothesis-testing
#' @param j The # hypotheses tested; used to compute a Bonferonni correction, if applicable;
#'          should remain at its default if multiple testing is not an issue (scalar)
#' @param df NULL (default) uses k - 3 degrees of freedom, where k is the number of bins
#' after input cleaning. A positive, finite numeric scalar overrides the degrees
#' of freedom used for the chi-square reference distribution.
#'
#' @section Precision metadata:
#' Successful computed results also carry a rita_test attribute with the
#' unrounded statistic and p.value, n_tested, precision, calibration and
#' details. It records existing computations without rerunning the test.
#' Unsupported or undefined results retain their existing sentinel/NA
#' representation and may lack this attribute. See rita_analysis for reporting
#' conventions.
#'
#' @return An object including the test statistic, p-value, and a significance flag (list)
#' @export
#'
#' @references Moore, D.S., (1986) Tests of the chi-squared type. In: D'agostino, R.B. and Stephens, M.A., eds.: Goodness-of-Fit Techniques. Marcel Dekker, New York.
#'
#' @examples
#' values <- rnorm(100)
#' x <- chisqTest(data = values)
#' k <- ceiling(2 * length(values)^(2/5))
#' approximate <- chisqTest(values, df = k - 3) # Explicit approximation, not exact.
chisqTest <- function(data, alpha = .05, j = 1, df = NULL) {
  if (!is.null(df) && (!is.numeric(df) || is.complex(df) || length(df)!=1L ||
      is.na(df) || !is.finite(df) || df<=0))
    stop("df must be NULL or a positive finite numeric scalar.",call.=FALSE)
  fit <- .rita_chisq_cells(data)
  if (is.null(df)) df <- fit$k-3
  p <- pchisq(fit$statistic,df=df,lower.tail=FALSE)
  result <- list(c(chiSq=round(fit$statistic,3)),c(`P-value`=round(p,3)),
       c(Sig.=p < alpha/j))
  .rita_test_info(result,fit$statistic,p,fit$n,"pearson-chi-square-approximation",
                  list(df=df,k=fit$k,expected_count=fit$expected))
}

# Private construction helper also exposes numerical cells for validation.
# Standardizing before constructing quantiles is equivalent to using fitted
# mean + sample SD * qnorm(p) in original units, without overflowing that sum.
.rita_chisq_cells <- function(data) {
  if (!is.numeric(data) || is.complex(data))
    stop("chisqTest requires numeric observations (a vector, matrix or array).",call.=FALSE)
  data <- as.vector(data)
  data <- data[!is.na(data)]
  n <- length(data)
  if (n<3L || any(!is.finite(data)))
    stop("chisqTest requires at least three finite observations after omitting NA/NaN.",
         call.=FALSE)
  limits <- range(data)
  center <- limits[1]/2 + limits[2]/2
  y <- data-center
  scale <- max(abs(y))
  if (!is.finite(scale) || scale<=0)
    stop("chisqTest requires nonconstant observations with positive variance.",call.=FALSE)
  y <- y/scale
  sigma <- sd(y)
  if (!is.finite(sigma) || sigma<=0)
    stop("chisqTest requires a finite, positive standardized sample variance.",call.=FALSE)
  z <- (y-mean(y))/sigma
  k <- ceiling(2*n^(2/5))
  breaks <- c(-Inf,qnorm(seq_len(k-1)/k),Inf)
  cell <- cut(z,breaks=breaks,labels=FALSE,right=TRUE,include.lowest=TRUE)
  counts <- tabulate(cell,nbins=k)
  if (anyNA(cell) || sum(counts)!=n)
    stop("chisqTest could not assign every usable observation to exactly one cell.",call.=FALSE)
  expected <- n/k
  list(statistic=sum((counts-expected)^2/expected),n=n,k=k,
       counts=counts,expected=expected,breaks=breaks)
}

# Reporting only: retain values already computed, without changing the legacy
# list elements, calibration, decisions, warning emission or RNG use.
.rita_test_info <- function(result,statistic,p,n,calibration,details=list(),reason=NULL) {
  flag <- unname(result[[3]])
  mc <- attr(result,"monte_carlo")
  if (n == 0L) {
    status <- "unavailable"
    calibration <- "not-computed"
  } else {
    if (is.null(reason)) {
      if (!is.finite(statistic) || statistic < 0)
        reason <- "The computed statistic is missing, nonfinite or negative."
      else if (!is.finite(p))
        reason <- "The computed p-value is missing or nonfinite."
      else if (p < 0 || p > 1)
        reason <- "The computed p-value is outside [0, 1]."
    }
    if (!is.null(reason)) {
      status <- "invalid-numerical-result"
    } else if (length(flag) != 1L || is.na(flag)) {
      status <- "unavailable"
      reason <- "The significance flag is undefined."
    } else if (isTRUE(details$clipped)) {
      status <- "approximation-boundary"
    } else if (!is.null(mc) && mc$exceedances == 0) {
      status <- "monte-carlo-floor"
    } else if (p == 0) {
      status <- "numerical-zero"
    } else {
      status <- "computed"
    }
  }
  unavailable <- status %in% c("unavailable", "invalid-numerical-result")
  attr(result,"rita_test") <- list(statistic=statistic,p.value=p,n_tested=n,
    precision=if(unavailable) "unavailable" else "unrounded-computation",
    calibration=calibration,details=details,status=status,reason=reason,
    decision=if(unavailable) "unavailable" else if(isTRUE(flag)) "reject" else "do not reject")
  result
}

Try the Rita package in your browser

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

Rita documentation built on Nov. 16, 2026, 5:07 p.m.