--- title: "Getting started with RChiSquare" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting started with RChiSquare} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} link-citations: true references: - author: - family: Cressie given: Noel - family: Read given: Timothy R. C. container-title: "Journal of the Royal Statistical Society: Series B" id: cressieread1984 issue: 3 issued: 1984 page: 440-464 title: Multinomial Goodness-of-Fit Tests type: article-journal volume: 46 - author: - family: Rolke given: Wolfgang container-title: The R Journal doi: 10.32614/RJ-2025-027 id: rolke2025 issue: 3 issued: 2025 page: 138-161 title: "Rgof and R2sample: Testing and Benchmarking for the Univariate Goodness-of-Fit and Two-Sample Problems" title-short: Rgof and R2sample type: article-journal volume: 17 - author: - family: Pearson given: Karl container-title: The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science doi: 10.1080/14786440009463897 id: pearson1900 issue: 302 issued: 1900 page: 157-175 title: On the Criterion that a Given System of Deviations from the Probable in the Case of a Correlated System of Variables Is Such that It Can Be Reasonably Supposed to Have Arisen from Random Sampling type: article-journal volume: 50 - author: - family: Fisher given: Ronald A. container-title: Journal of the Royal Statistical Society id: fisher1922 issue: 1 issued: 1922 page: 87-94 title: "On the Interpretation of [χ²]{.nocase} from Contingency Tables, and the Calculation of P" type: article-journal volume: 85 - author: - family: Wilks given: Samuel S. container-title: The Annals of Mathematical Statistics doi: 10.1214/aoms/1177732360 id: wilks1938 issue: 1 issued: 1938 page: 60-62 title: The Large-Sample Distribution of the Likelihood Ratio for Testing Composite Hypotheses type: article-journal volume: 9 - author: - family: Rolke given: Wolfgang id: pkg_MDgof issued: 2026 note: R package title: "MDgof: Various Methods for the Goodness-of-Fit Problem in D>1 Dimensions" title-short: MDgof type: book url: "https://CRAN.R-project.org/package=MDgof" - author: - family: Rolke given: Wolfgang id: pkg_MD2sample issued: 2026 note: R package title: "MD2sample: Multivariate Two-Sample Tests" title-short: MD2sample type: book url: "https://CRAN.R-project.org/package=MD2sample" - author: - family: Moore given: David S. - family: Spruill given: M. C. container-title: The Annals of Statistics doi: 10.1214/aos/1176343125 id: moore_spruill_1975 issue: 3 issued: 1975 page: 599-616 title: Unified Large-Sample Theory of General Chi-Squared Statistics for Tests of Fit type: article-journal volume: 3 - author: - family: Chernoff given: Herman - family: Lehmann given: E. L. container-title: The Annals of Mathematical Statistics id: ChernoffLehmann1954 issued: 1954 page: 579-586 title: The Use of Maximum Likelihood Estimates in Chi-Square Tests for Goodness of Fit type: article-journal volume: 25 --- ```{r setup, include=FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE) ``` ## What is RChiSquare for? **RChiSquare** provides chi-square [@pearson1900] and Cressie--Read power-divergence [@cressieread1984] tests for goodness-of-fit and for comparing two independent samples. It supports both **discrete observations** (categories, counts, or integer-valued variables) and **continuous observations**, including multivariate data. The same public entry point, `chi_test()`, selects the appropriate test from the data type, dimension, and problem. The public interface infers the problem and dimension from the supplied inputs. For discrete numeric data, specify `type = "discrete"` when automatic classification might be ambiguous. A **goodness-of-fit (GOF) test** compares one sample with a fully specified null distribution, possibly including parameters estimated from the sample. A **two-sample test** asks whether two independent samples have the same distribution, without requiring the user to specify that common distribution. In both cases the package groups observations into cells and compares observed and expected counts. Small cells may be merged, because the chi-square approximation becomes unreliable when expected counts are too low. Each estimated parameter reduces the degrees of freedom by one [@fisher1922]. For continuous observations, the package can form **equal-space (ES)** or **equal-probability (EP)** partitions. ES uses intervals of comparable width; EP uses intervals with comparable probability under the relevant reference distribution. In multiple dimensions, partitions form rectangular grids. Users can choose `nbins` or supply exact boundaries through `bins`, in both the tests and the power calculations. Discrete data instead use their natural categories, with merging as needed. The package also estimates **statistical power** under a specified alternative using `chi_power()`, searches for a sample size meeting a power target using `chi_sample_size()`, and compares analytic and simulation-based power calculations using `compare_power()`. Simulation estimates have Monte Carlo uncertainty, so a small replication count is useful for exploration but not for a final study design. The analytic calculations rely on large-sample approximations; they use an alternative CDF or probability mass function when one is supplied and otherwise estimate the alternative cell probabilities from generated data. The examples rely on automatic problem and dimension detection. Discrete examples specify `type = "discrete"` where numeric values could be mistaken for continuous ones. ## Basic workflow ```{r basic} set.seed(101) x <- rnorm(200, mean = 0.25) res <- RChiSquare::chi_test(x, "pnorm") res ``` As with `ks.test()`, the null distribution can be given by name, with fixed parameters passed by name (`chi_test(x, "pnorm", mean = 1, sd = 2)`); a CDF function such as `y = pnorm` works as well. In a two-sample test, `y` is the second dataset. Printing gives a compact report; `summary(res)` adds fitted parameters and the cells, `RChiSquare::chi_cells(res, "EP")` returns the cells (observed and expected counts, residuals and each cell's contribution to the statistic), and `RChiSquare::as_htest(res, "EP")` converts the result to a standard `htest` object. For continuous data the result has one row for each partition. Decide in advance which partition to use, and use `partition = "ES"` or `"EP"` to report only that one: choosing the smaller p-value after seeing both inflates the Type I error. The result is a numeric table (continuous data) or a named vector (discrete data) with entries `statistic`, `p.value`, `df`, `K` (final cells) and `reject`. For continuous tests use `res[, c("statistic", "p.value", "df", "K")]`; for discrete tests use `res[c("statistic", "p.value", "df", "K")]`. Choose a significance threshold when interpreting the p-values; the test itself does not require a particular threshold. ## The interface at a glance Estimated parameters are named in `phat`; starting values come from the moments of the data and the final estimates minimize the chi-square statistic on the final cells. Estimating the parameters on the cells keeps the usual chi-square reference distribution with $K-1-r$ degrees of freedom for $r$ estimated parameters; maximum likelihood estimates from the raw data would change the limiting distribution [@ChernoffLehmann1954]. Large-sample theory for cells that depend on the data is given by @moore_spruill_1975. ```{r glance-phat} res <- RChiSquare::chi_test(x, "pnorm", phat = c("mean", "sd"), partition = "EP") summary(res) ``` Categorical data take a vector of category probabilities, as in `chisq.test()`: ```{r glance-p} set.seed(1) colour <- sample(c("red", "green", "blue"), 150, replace = TRUE, prob = c(.5, .3, .2)) RChiSquare::chi_test(colour, p = c(red = .5, green = .3, blue = .2)) ``` Two samples can also be given with a formula and a grouping variable with two levels: ```{r glance-formula} RChiSquare::chi_test(mag ~ depth > 300, data = datasets::quakes) ``` Missing values are removed with a message. ### Looking inside a result `chi_cells()` lists the final cells with observed and expected counts, Pearson residuals and each cell's contribution to the statistic; the contributions sum to the statistic. `as_htest()` returns a standard `htest` object for code that expects one. ```{r glance-cells} res <- RChiSquare::chi_test(x, "pnorm", partition = "EP") RChiSquare::chi_cells(res, "EP") RChiSquare::as_htest(res, "EP") ``` ## Continuous data: one dimension ### Goodness-of-fit ```{r continuous-1d-gof} set.seed(102) x <- rnorm(240, mean = 0.35) res <- RChiSquare::chi_test( x, "pnorm", nbins = 7 ) res[, c("statistic", "p.value", "df", "K")] ``` To choose boundaries yourself, use a vector that spans the range (here, the whole real line). The package can still merge cells when their expected counts are too small. ```{r continuous-1d-custom} res <- RChiSquare::chi_test( x, y = pnorm, bins = c(-Inf, -1.5, -0.5, 0.5, 1.5, Inf) ) res[, c("statistic", "p.value", "df", "K")] ``` ### Two independent samples ```{r continuous-1d-two} set.seed(103) x <- rnorm(180) y <- rnorm(210, mean = 0.4) res <- RChiSquare::chi_test( x, y, nbins = 7 ) res[, c("statistic", "p.value", "df", "K")] ``` ## Discrete data: one dimension ### Goodness-of-fit A binomial null is given by name, with its parameters fixed through `...`. A CDF function, such as `function(z) pbinom(z, 5, 0.4)`, works as well. ```{r discrete-1d-gof} set.seed(104) x <- rbinom(300, size = 5, prob = 0.4) RChiSquare::chi_test(x, "pbinom", size = 5, prob = 0.4) ``` Parameters can also be estimated. The `discoveries` data set gives the number of great inventions and scientific discoveries in each year from 1860 to 1959. Are these counts Poisson? Small tail categories are merged, and one degree of freedom is lost for the estimated rate. ```{r discrete-1d-discoveries} res <- RChiSquare::chi_test(as.numeric(datasets::discoveries), "ppois", phat = "lambda") summary(res) ``` A negative binomial null allows for overdispersion; `pnbinom` is parametrized here by `size` and `mu`: ```{r discrete-1d-nbinom} RChiSquare::chi_test(as.numeric(datasets::discoveries), "pnbinom", phat = c("size", "mu")) ``` ### Two independent samples ```{r discrete-1d-two} set.seed(105) x <- rpois(250, lambda = 2) y <- rpois(270, lambda = 2.5) res <- RChiSquare::chi_test( x, y, type = "discrete" ) res[c("statistic", "p.value", "df", "K")] ``` ## Continuous data: two dimensions Each row is one observation and each column is a coordinate. A joint CDF must accept a **vector of coordinates** and return one probability. For independent standard normal coordinates, the joint CDF is the product of the marginal CDFs. ```{r continuous-2d-gof} set.seed(106) x2 <- cbind(rnorm(450), rnorm(450, mean = 0.25)) normal2_cdf <- function(z) prod(pnorm(z)) res <- RChiSquare::chi_test( x2, y = normal2_cdf, nbins = c(5, 5) ) res[, c("statistic", "p.value", "df", "K")] ``` ```{r continuous-2d-two} set.seed(107) x2 <- cbind(rnorm(350), rnorm(350)) y2 <- cbind(rnorm(380, 0.3), rnorm(380)) res <- RChiSquare::chi_test( x2, y2, nbins = c(5, 5) ) res[, c("statistic", "p.value", "df", "K")] ``` For custom two-dimensional cells, specify one boundary vector per column: ```{r continuous-2d-custom} set.seed(1071) x2 <- cbind(rnorm(350), rnorm(350, mean = 0.25)) res <- RChiSquare::chi_test( x2, y = normal2_cdf, bins = list(c(-Inf, -1, 0, 1, Inf), c(-Inf, -1, 0, 1, Inf)) ) res[, c("statistic", "p.value", "df", "K"), drop = FALSE] ``` ## Discrete data: two dimensions The following null treats the two coordinates as independent Poisson variables. The joint CDF is again a product of marginal CDFs. ```{r discrete-2d-gof} set.seed(108) x2 <- cbind(rpois(500, 2), rpois(500, 3)) pois2_cdf <- function(z) prod(ppois(z, lambda = c(2, 3))) res <- RChiSquare::chi_test( x2, y = pois2_cdf, type = "discrete" ) res[c("statistic", "p.value", "df", "K")] ``` ```{r discrete-2d-two} set.seed(109) x2 <- cbind(rpois(350, 2), rpois(350, 2)) y2 <- cbind(rpois(370, 2.4), rpois(370, 2)) res <- RChiSquare::chi_test( x2, y2, type = "discrete" ) res[c("statistic", "p.value", "df", "K")] ``` ## Three-dimensional data The same multidimensional interface handles three or more coordinates. Three-dimensional grids can contain many cells, so use a sufficient sample size and start with relatively few bins per coordinate. ```{r continuous-3d} set.seed(110) x3 <- cbind(rnorm(850), rnorm(850), rnorm(850, 0.25)) normal3_cdf <- function(z) prod(pnorm(z)) res <- RChiSquare::chi_test( x3, y = normal3_cdf, nbins = c(4, 4, 4) ) res[, c("statistic", "p.value", "df", "K")] y3 <- cbind(rnorm(900, 0.3), rnorm(900), rnorm(900)) res <- RChiSquare::chi_test( x3, y3, nbins = c(4, 4, 4) ) res[, c("statistic", "p.value", "df", "K")] ``` ```{r discrete-3d} set.seed(111) x3 <- cbind(rbinom(600, 1, 0.5), rbinom(600, 1, 0.5), rbinom(600, 1, 0.5)) bernoulli3_cdf <- function(z) prod(pbinom(z, size = 1, prob = 0.5)) res <- RChiSquare::chi_test( x3, y = bernoulli3_cdf, type = "discrete" ) res[c("statistic", "p.value", "df", "K")] y3 <- cbind(rbinom(650, 1, 0.65), rbinom(650, 1, 0.5), rbinom(650, 1, 0.5)) res <- RChiSquare::chi_test( x3, y3, type = "discrete" ) res[c("statistic", "p.value", "df", "K")] ``` ## A real-data example: earthquakes near Fiji The `quakes` data give the location (longitude, latitude, depth) and magnitude of 1,000 earthquakes. Do the locations of stronger and weaker earthquakes have the same three-dimensional distribution? The formula interface splits the data by a grouping variable with two levels. ```{r quakes} quakes <- datasets::quakes quakes$group <- factor(ifelse(quakes$mag >= median(quakes$mag), "higher", "lower")) fit <- RChiSquare::chi_test(cbind(long, lat, depth) ~ group, data = quakes, family = "likelihood", nbins = c(4, 4, 4)) fit ``` Both partitions reject equality decisively. The cells with the largest contributions show where the two groups differ (`x` is the higher-magnitude group): ```{r quakes-cells} cells <- RChiSquare::chi_cells(fit, "EP") head(cells[order(-cells$contribution), ], 5) ``` Because the partition is built from the pooled data and then merged, a permutation p-value avoids relying on the chi-square approximation: ```{r quakes-permutation} RChiSquare::chi_test(cbind(long, lat, depth) ~ group, data = quakes, family = "likelihood", nbins = c(4, 4, 4), p_method = "permutation", B = 999, seed = 1) ``` ## Other statistics, permutation and bootstrap p-values `family` selects a member of the Cressie--Read family [@cressieread1984]: `"pearson"` (default), `"likelihood"` [the likelihood-ratio statistic, @wilks1938], `"freeman-tukey"`, `"modified-likelihood"`, `"neyman"`, `"cressie-read"` ($\lambda = 2/3$), or `"custom"` with any `lambda`. For two-sample tests, `p_method = "permutation"` replaces the chi-square approximation by `B` random relabellings of the pooled data; `seed` makes the result reproducible. ```{r family-permutation} set.seed(112) x <- rnorm(60) y <- rnorm(70, mean = 0.5) RChiSquare::chi_test(x, y, nbins = 5, family = "likelihood") RChiSquare::chi_test(x, y, nbins = 5, family = "likelihood", p_method = "permutation", B = 999, seed = 1) ``` For goodness-of-fit tests, `p_method = "bootstrap"` gives a parametric bootstrap p-value: `B` samples of the observed size are drawn from the fitted null and the complete test, including parameter estimation and cell construction, is repeated on each. It does not rely on the chi-square approximation or on the degrees of freedom of a composite null. Samples are generated automatically for a null given by name, a PMF with `support` or `p`, and one-dimensional data; otherwise supply a generator `rnull(n, theta)`. ```{r bootstrap} RChiSquare::chi_test(as.numeric(datasets::discoveries), "ppois", phat = "lambda", p_method = "bootstrap", B = 199, seed = 1) ``` ## Power calculations Power is the probability that a test rejects a false null hypothesis at a chosen significance level `alpha`. `chi_power()` takes a generator of data under the alternative and the same null specification as `chi_test()`. For Pearson's statistic the default is an analytic approximation (`method = "analytic"`), which avoids repeating the test many times; `method = "simulation"` estimates the rejection rate over `B` simulated data sets and works for every `family`. The analytic method needs the alternative cell probabilities. With a known alternative CDF (`alt_cdf`) they are computed exactly. Otherwise they are estimated from reference data drawn from the generator, whose size is chosen automatically so that each cell probability has a standard error of about 0.001. When the test's partition depends on the data, as for two-sample and multidimensional tests, power is averaged over the partitions of successive reference data sets until the Monte Carlo error of the average is below 0.002. `B` is used only by simulation. The examples use `cores = 1`; by default larger calculations run in parallel. ### Goodness-of-fit ```{r power-gof} # Known alternative CDF: exact alternative cell probabilities. RChiSquare::chi_power(function(n) rnorm(n, 0.3), "pnorm", alt_cdf = function(z) pnorm(z, 0.3), n = 100, nbins = c(5, 8)) # Composite null: normal with estimated mean and sd, data from t(4). RChiSquare::chi_power(function(n) rt(n, 4), "pnorm", phat = c("mean", "sd"), n = 200, nbins = 8, cores = 1, seed = 1) # Discrete: Poisson with estimated rate, overdispersed data. RChiSquare::chi_power(function(n) rnbinom(n, size = 5, mu = 2.5), "ppois", phat = "lambda", n = 150, type = "discrete", cores = 1, seed = 1) # Two dimensions: joint null CDF of a coordinate vector. RChiSquare::chi_power(function(n) cbind(rnorm(n, 0.2), rnorm(n)), function(z) prod(pnorm(z)), alt_cdf = function(z) prod(pnorm(z, mean = c(0.2, 0))), n = 300, nbins = c(4, 4), cores = 1, seed = 1) ``` The fitted-normal example shows how strongly power can depend on the partition: ES cells, which are wider in the tails, detect the heavier tails of the t distribution far better than EP cells. ### Two samples A two-sample generator takes the two sample sizes `n` and `m` and returns `list(x = ..., y = ...)`. ```{r power-two} RChiSquare::chi_power(function(n, m) list(x = rnorm(n), y = rnorm(m, 0.3)), n = 150, m = 150, nbins = 7, cores = 1, seed = 1) RChiSquare::chi_power(function(n, m) list(x = rbinom(n, 4, 0.5), y = rbinom(m, 4, 0.57)), n = 250, m = 250, type = "discrete", cores = 1, seed = 1) RChiSquare::chi_power(function(n, m) list(x = cbind(rnorm(n), rnorm(n)), y = cbind(rnorm(m, 0.3), rnorm(m))), n = 300, m = 300, nbins = c(4, 4), cores = 1, seed = 1) ``` The same calls work for three-dimensional data and for discrete multidimensional data (with `pmnull` and `support`, as for `chi_test()`). ### Power curves Vectors of scenario parameters `par1` (and `par2`) give a power curve. They are passed to the generator and, matched by name, to `alt_cdf`: ```{r power-curve} RChiSquare::chi_power(function(n, mu) rnorm(n, mu), "pnorm", alt_cdf = function(z, mu) pnorm(z, mu), par1 = c(0, 0.1, 0.2, 0.3, 0.4), n = 150, nbins = 7, cores = 1, seed = 1) ``` At `mu = 0` the null hypothesis is true and the power equals `alpha`. ### Power of the bootstrap test When the test will use bootstrap p-values, its power can be simulated with `p_method = "bootstrap"`. Running a bootstrap test in every replication would need `B^2` tests; instead the null distribution of the statistic is simulated once and every test under the alternative is compared with it, so `2B` tests suffice. For a composite null the null samples come from the member of the null family closest to the alternative. ```{r power-bootstrap} RChiSquare::chi_power(function(n) rnbinom(n, size = 5, mu = 2.5), "ppois", phat = "lambda", n = 150, type = "discrete", method = "simulation", p_method = "bootstrap", B = 100, cores = 1, seed = 1) ``` Compare with the analytic power of the asymptotic test above (about 0.70); `B = 100` only keeps the example fast. ## Sample-size planning `chi_sample_size()` repeatedly calls `chi_power()` to search for the first sample size with estimated power at least `power`. For continuous tests, specify a **single** `nbins` configuration and use `partition = "ES"` or `"EP"` to select a partition. The `bins` argument to `chi_test()` instead specifies custom cell boundaries. The returned sample size is an estimate, particularly when power is simulated. The analytic search is fast, especially with a known alternative CDF: ```{r sample-size} RChiSquare::chi_sample_size(function(n) rnorm(n, 0.3), "pnorm", alt_cdf = function(z) pnorm(z, 0.3), power = 0.8, nbins = 7, partition = "EP", method = "analytic", seed = 1) ``` With `method = "simulation"` (the default) the analytic estimate is refined by simulated power, which takes longer: ```{r sample-size-simulation, eval=FALSE} RChiSquare::chi_sample_size(function(n) rnorm(n, 0.3), "pnorm", alt_cdf = function(z) pnorm(z, 0.3), power = 0.8, nbins = 7, partition = "EP", B = 1000, seed = 1) ``` ## Compare analytic and simulation power `compare_power()` accepts the public `chi_power` function and passes the design options to it. It calculates both methods; `plot = TRUE` draws them, which is useful over a range of alternatives or bin counts. For a single design a table is clearer: ```{r compare-power} cmp <- RChiSquare::compare_power( RChiSquare::chi_power, rxy = function(n) rnorm(n, mean = 0.3), y = "pnorm", alt_cdf = function(z) pnorm(z, mean = 0.3), n = 150, nbins = 7, B = 500, cores = 1, seed = 1, plot = FALSE, verbose = FALSE ) d <- cmp$plot_data[cmp$plot_data$method %in% c("analytic", "simulation"), ] d$bins <- factor(d$bins, levels = c("ES", "EP")) round(xtabs(power ~ bins + method, data = d), 3) ``` With `B = 500` the simulated values have a Monte Carlo standard error of about 0.02. ## Practical guidance * **Select the correct problem:** GOF uses a null CDF or PMF; two-sample tests use two datasets. * **Specify the data type:** numeric values are not necessarily continuous; counts and category codes are discrete. * **Supply one row per multivariate observation:** the columns represent coordinates. * **Control cell counts:** very fine partitions can create sparse cells; check the resulting merged partition and degrees of freedom. * **Choose the partition in advance:** ES and EP results can differ because the partitions differ, and there is no universally best partition. Selecting the one with the smaller p-value after seeing both inflates the Type I error; use `partition = "ES"` or `"EP"` to report only the chosen one. * **Check the chi-square approximation when in doubt:** with estimated parameters, data-dependent cells or sparse multidimensional grids, use `p_method = "bootstrap"` (goodness-of-fit) or `"permutation"` (two samples) instead of the asymptotic p-values. * **Treat power estimates as estimates:** repeat important simulations with larger `B` and check stability before making study-design decisions. * **Consider other tests:** chi-square tests are general but not always the most powerful. Tests based on the empirical distribution function and many others are available in 'Rgof' and 'R2sample' [@rolke2025] for one-dimensional data and in 'MDgof' [@pkg_MDgof] and 'MD2sample' [@pkg_MD2sample] for multivariate data. For argument details, use `?RChiSquare::chi_test`, `?RChiSquare::chi_power`, `?RChiSquare::chi_sample_size`, `?RChiSquare::chi_cells`, and `?RChiSquare::compare_power`. To find this vignette after installing the package, run `vignette("getting-started", package = "RChiSquare")`. ## References