Getting started with RChiSquare

What is RChiSquare for?

RChiSquare provides chi-square (Pearson 1900) and Cressie–Read power-divergence (Cressie and Read 1984) 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 (Fisher 1922).

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

set.seed(101)
x <- rnorm(200, mean = 0.25)
res <- RChiSquare::chi_test(x, "pnorm")
res
#> 
#>  Pearson goodness-of-fit test (continuous, 1D)
#> 
#> data:  x
#>    statistic df p.value cells
#> ES     8.846  6 0.18240     7
#> EP     12.17  6 0.05828     7
#> ES = equal-space, EP = equal-probability partition; choose one in advance.

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 (Chernoff and Lehmann 1954). Large-sample theory for cells that depend on the data is given by Moore and Spruill (1975).

res <- RChiSquare::chi_test(x, "pnorm", phat = c("mean", "sd"), partition = "EP")
summary(res)
#> Pearson goodness-of-fit test (continuous, 1D) 
#> data:  x
#> Type: continuous  | Dimension: 1D 
#> 
#>    statistic df p.value cells
#> EP     3.059  6  0.8014     9
#> 
#> Final fitted parameters (minimum chi-square on the final cells):
#>      mean    sd
#> EP 0.2284 1.011
#> 
#> Cells (EP partition) - see chi_cells():
#>                cell observed expected residual contribution
#>     [-Inf, -0.9703)       24    23.56  0.09053     0.008195
#>  [-0.9703, -0.5293)       18    21.78  -0.8107       0.6573
#>  [-0.5293, -0.2062)       25    21.37   0.7847       0.6158
#>  [-0.2062, 0.07526)       24    21.24   0.5988       0.3586
#>   [0.07526, 0.3455)       20    21.27  -0.2755      0.07591
#>    [0.3455, 0.6271)       18    21.45  -0.7442       0.5538
#>    [0.6271, 0.9501)       25    21.81   0.6835       0.4671
#>     [0.9501, 1.391)       20    22.52  -0.5313       0.2823
#>        [1.391, Inf]       26       25   0.2007      0.04029

Categorical data take a vector of category probabilities, as in chisq.test():

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))
#> 
#>  Pearson goodness-of-fit test (discrete, 1D)
#> 
#> data:  colour
#>  statistic df p.value cells
#>      1.769  2  0.4129     3

Two samples can also be given with a formula and a grouping variable with two levels:

RChiSquare::chi_test(mag ~ depth > 300, data = datasets::quakes)
#> 
#>  Pearson two-sample test (discrete, 1D)
#> 
#> data:  mag by depth > 300
#>  statistic df   p.value cells
#>      73.23 18 1.275e-08    19

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.

res <- RChiSquare::chi_test(x, "pnorm", partition = "EP")
RChiSquare::chi_cells(res, "EP")
#>                cell observed expected   residual contribution
#> 1    [-Inf, -1.068)       21 28.57143 -1.4164846   2.00642857
#> 2 [-1.068, -0.5659)       16 28.57143 -2.3518989   5.53142857
#> 3  [-0.5659, -0.18)       33 28.57143  0.8285098   0.68642857
#> 4     [-0.18, 0.18)       28 28.57143 -0.1069045   0.01142857
#> 5    [0.18, 0.5659)       30 28.57143  0.2672612   0.07142857
#> 6   [0.5659, 1.068)       36 28.57143  1.3897585   1.93142857
#> 7      [1.068, Inf]       36 28.57143  1.3897585   1.93142857
RChiSquare::as_htest(res, "EP")
#> 
#>  Pearson goodness-of-fit test (continuous, 1D)
#> 
#> data:  x
#> X-squared = 12.17, df = 6, p-value = 0.05828

Continuous data: one dimension

Goodness-of-fit

set.seed(102)
x <- rnorm(240, mean = 0.35)
res <- RChiSquare::chi_test(
  x, "pnorm", nbins = 7
)
res[, c("statistic", "p.value", "df", "K")]
#>    statistic      p.value df K
#> ES  40.29422 3.987158e-07  6 7
#> EP  35.27500 3.811754e-06  6 7

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.

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")]
#>    statistic     p.value df K
#> ES  42.10983 1.58297e-08  4 5
#> EP  42.10983 1.58297e-08  4 5

Two independent samples

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")]
#>    statistic    p.value df K
#> ES  11.33627 0.04510572  5 6
#> EP  12.77439 0.04676189  6 7

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.

set.seed(104)
x <- rbinom(300, size = 5, prob = 0.4)
RChiSquare::chi_test(x, "pbinom", size = 5, prob = 0.4)
#> 
#>  Pearson goodness-of-fit test (discrete, 1D)
#> 
#> data:  x
#>  statistic df p.value cells
#>      1.299  4  0.8615     5

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.

res <- RChiSquare::chi_test(as.numeric(datasets::discoveries), "ppois",
                            phat = "lambda")
summary(res)
#> Pearson goodness-of-fit test (discrete, 1D) 
#> data:  as.numeric(datasets::discoveries)
#> Type: discrete  | Dimension: 1D 
#> 
#>   statistic df p.value cells
#> 1     6.628  4  0.1569     6
#> 
#> Final fitted parameters (minimum chi-square on the final cells):
#>  lambda
#>   3.089
#> 
#> Cells - see chi_cells():
#>  cell observed expected residual contribution
#>  <= 1       21    18.62   0.5521       0.3048
#>     2       26    21.73   0.9167       0.8404
#>     3       20    22.37  -0.5021       0.2521
#>     4       12    17.28    -1.27        1.614
#>     5        7    10.68   -1.126        1.267
#>  >= 6       14     9.32    1.533        2.349

A negative binomial null allows for overdispersion; pnbinom is parametrized here by size and mu:

RChiSquare::chi_test(as.numeric(datasets::discoveries), "pnbinom",
                     phat = c("size", "mu"))
#> 
#>  Pearson goodness-of-fit test (discrete, 1D)
#> 
#> data:  as.numeric(datasets::discoveries)
#>  statistic df p.value cells
#>       4.34  5  0.5016     8
#> 
#> Final fitted parameters (minimum chi-square on the final cells):
#>   size    mu
#>  6.239 3.059

Two independent samples

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")]
#>  statistic    p.value         df          K 
#> 15.2116222  0.0333804  7.0000000  8.0000000

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.

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")]
#>    statistic    p.value df  K
#> ES  32.86239 0.01734173 18 19
#> EP  32.94266 0.10528915 24 25
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")]
#>    statistic    p.value df  K
#> ES  21.59365 0.06198656 13 14
#> EP  36.98980 0.04386261 24 25

For custom two-dimensional cells, specify one boundary vector per column:

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]
#>    statistic     p.value df  K
#> ES  31.93058 0.006579694 15 16
#> EP  31.93058 0.006579694 15 16

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.

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")]
#> statistic   p.value        df         K 
#> 43.195350  0.134096 34.000000 35.000000
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")]
#>  statistic    p.value         df          K 
#> 38.1765704  0.3707755 36.0000000 37.0000000

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.

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")]
#>    statistic      p.value df  K
#> ES  83.15061 5.326251e-06 34 35
#> EP 157.20198 5.187016e-10 63 64
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")]
#>    statistic      p.value df  K
#> ES   78.4901 8.825860e-06 32 33
#> EP  125.5989 4.721479e-06 63 64
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")]
#> statistic   p.value        df         K 
#> 4.1866667 0.7580436 7.0000000 8.0000000
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")]
#>    statistic      p.value           df            K 
#> 2.516673e+01 7.088439e-04 7.000000e+00 8.000000e+00

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.

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
#> 
#>  Likelihood-ratio two-sample test (continuous, MD)
#> 
#> data:  cbind(long, lat, depth) by group
#>    statistic df   p.value cells
#> ES     112.1 20 7.969e-15    21
#> EP     162.2 33 < 2.2e-16    34
#> ES = equal-space, EP = equal-probability partition; choose one in advance.

Both partitions reject equality decisively. The cells with the largest contributions show where the two groups differ (x is the higher-magnitude group):

cells <- RChiSquare::chi_cells(fit, "EP")
head(cells[order(-cells$contribution), ], 5)
#>            cell  x  y expected_x expected_y residual_x residual_y contribution
#> 13 R13 (1 cell) 14  0      7.224      6.776   2.521068  -2.603075     18.52616
#> 9   R9 (1 cell) 43 12     28.380     26.620   2.744361  -2.833631     16.61218
#> 5   R5 (1 cell) 17  1      9.288      8.712   2.530498  -2.612812     16.22326
#> 28 R28 (1 cell)  1 13      7.224      6.776  -2.315692   2.391018     12.98580
#> 7   R7 (1 cell) 28  8     18.576     17.424   2.186549  -2.257675     10.52420

Because the partition is built from the pooled data and then merged, a permutation p-value avoids relying on the chi-square approximation:

RChiSquare::chi_test(cbind(long, lat, depth) ~ group, data = quakes,
                     family = "likelihood", nbins = c(4, 4, 4),
                     p_method = "permutation", B = 999, seed = 1)
#> 
#>  Likelihood-ratio two-sample test (continuous, MD)
#> 
#> data:  cbind(long, lat, depth) by group
#>    statistic df p.value cells
#> ES     112.1 20   0.001    21
#> EP     162.2 33   0.001    34
#> p-values from 999 label permutations.
#> ES = equal-space, EP = equal-probability partition; choose one in advance.

Other statistics, permutation and bootstrap p-values

family selects a member of the Cressie–Read family (Cressie and Read 1984): "pearson" (default), "likelihood" (the likelihood-ratio statistic, Wilks 1938), "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.

set.seed(112)
x <- rnorm(60)
y <- rnorm(70, mean = 0.5)
RChiSquare::chi_test(x, y, nbins = 5, family = "likelihood")
#> 
#>  Likelihood-ratio two-sample test (continuous, 1D)
#> 
#> data:  x and y
#>    statistic df p.value cells
#> ES      4.57  3 0.20615     4
#> EP     8.751  4 0.06764     5
#> ES = equal-space, EP = equal-probability partition; choose one in advance.
RChiSquare::chi_test(x, y, nbins = 5, family = "likelihood",
                     p_method = "permutation", B = 999, seed = 1)
#> 
#>  Likelihood-ratio two-sample test (continuous, 1D)
#> 
#> data:  x and y
#>    statistic df p.value cells
#> ES      4.57  3   0.238     4
#> EP     8.751  4   0.079     5
#> p-values from 999 label permutations.
#> ES = equal-space, EP = equal-probability partition; choose one in advance.

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).

RChiSquare::chi_test(as.numeric(datasets::discoveries), "ppois",
                     phat = "lambda", p_method = "bootstrap", B = 199, seed = 1)
#> 
#>  Pearson goodness-of-fit test (discrete, 1D)
#> 
#> data:  as.numeric(datasets::discoveries)
#>  statistic df p.value cells
#>      6.628  4   0.225     6
#> p-values from 199 parametric bootstrap samples from the fitted null.
#> 
#> Final fitted parameters (minimum chi-square on the final cells):
#>  lambda
#>   3.089

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

# 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))
#> 
#>      Chi-square goodness-of-fit power calculation (continuous, 1D)
#> 
#>    method partition nbins K df  power
#>  analytic        ES     5 5  4 0.6217
#>  analytic        EP     5 5  4 0.6077
#>  analytic        ES     8 6  5 0.5914
#>  analytic        EP     8 8  7 0.5352
#> 
#> Analytic: fixed-alternative approximation; summary() shows the alternatives.

# 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)
#> 
#>      Chi-square goodness-of-fit power calculation (continuous, 1D)
#> 
#>    method partition nbins K df  power
#>  analytic        ES     8 8  5 0.4991
#>  analytic        EP     8 8  5 0.1279
#> 
#> Analytic: fixed-alternative approximation; summary() shows the alternatives.

# 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)
#> 
#>      Chi-square goodness-of-fit power calculation (discrete, 1D)
#> 
#>    method K df  power
#>  analytic 7  5 0.7007
#> 
#> Analytic: fixed-alternative approximation; summary() shows the alternatives.

# 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)
#> 
#>      Chi-square goodness-of-fit power calculation (continuous, MD)
#> 
#>    method partition nbins  power
#>  analytic        ES   4x4 0.5296
#>  analytic        EP   4x4 0.4808
#> 
#> Analytic: fixed-alternative approximation; summary() shows the alternatives.

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 = ...).

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)
#> 
#>      Chi-square two-sample power calculation (continuous, 1D)
#> 
#>    method partition nbins K df  power
#>  analytic        ES     7 5  4 0.4649
#>  analytic        EP     7 7  6 0.4065
#> 
#> Analytic: fixed-alternative approximation; summary() shows the alternatives.

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)
#> 
#>      Chi-square two-sample power calculation (discrete, 1D)
#> 
#>    method  power
#>  analytic 0.7059
#> 
#> Analytic: fixed-alternative approximation; summary() shows the alternatives.

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)
#> 
#>      Chi-square two-sample power calculation (continuous, MD)
#> 
#>    method partition nbins  power
#>  analytic        ES   4x4 0.5762
#>  analytic        EP   4x4 0.5240
#> 
#> Analytic: fixed-alternative approximation; summary() shows the alternatives.

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:

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)
#> 
#>      Chi-square goodness-of-fit power curve (continuous, 1D)
#> 
#>         ES     EP
#> 0   0.0500 0.0500
#> 0.1 0.1158 0.1140
#> 0.2 0.3891 0.3788
#> 0.3 0.7717 0.7612
#> 0.4 0.9612 0.9602

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.

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)
#> 
#>      Chi-square goodness-of-fit power calculation (discrete, 1D)
#> 
#>      method power
#>  simulation  0.64
#> 
#> Simulated: rejection rate of the parametric-bootstrap test (critical values from 100 null samples).

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:

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)
#> 
#>      Chi-square sample size calculation
#> 
#>              n = 170
#>          power = 0.8194
#>         target = 0.8
#>         method = analytic
#>      partition = EP

With method = "simulation" (the default) the analytic estimate is refined by simulated power, which takes longer:

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:

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)
#>     method
#> bins analytic simulation
#>   ES    0.772      0.752
#>   EP    0.761      0.742

With B = 500 the simulated values have a Monte Carlo standard error of about 0.02.

Practical guidance

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

Chernoff, Herman, and E. L. Lehmann. 1954. “The Use of Maximum Likelihood Estimates in Chi-Square Tests for Goodness of Fit.” The Annals of Mathematical Statistics 25: 579–86.
Cressie, Noel, and Timothy R. C. Read. 1984. “Multinomial Goodness-of-Fit Tests.” Journal of the Royal Statistical Society: Series B 46 (3): 440–64.
Fisher, Ronald A. 1922. “On the Interpretation of χ² from Contingency Tables, and the Calculation of P.” Journal of the Royal Statistical Society 85 (1): 87–94.
Moore, David S., and M. C. Spruill. 1975. “Unified Large-Sample Theory of General Chi-Squared Statistics for Tests of Fit.” The Annals of Statistics 3 (3): 599–616. https://doi.org/10.1214/aos/1176343125.
Pearson, Karl. 1900. “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.” The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science 50 (302): 157–75. https://doi.org/10.1080/14786440009463897.
Rolke, Wolfgang. 2025. “Rgof and R2sample: Testing and Benchmarking for the Univariate Goodness-of-Fit and Two-Sample Problems.” The R Journal 17 (3): 138–61. https://doi.org/10.32614/RJ-2025-027.
Rolke, Wolfgang. 2026a. MD2sample: Multivariate Two-Sample Tests. https://CRAN.R-project.org/package=MD2sample.
Rolke, Wolfgang. 2026b. MDgof: Various Methods for the Goodness-of-Fit Problem in D>1 Dimensions. https://CRAN.R-project.org/package=MDgof.
Wilks, Samuel S. 1938. “The Large-Sample Distribution of the Likelihood Ratio for Testing Composite Hypotheses.” The Annals of Mathematical Statistics 9 (1): 60–62. https://doi.org/10.1214/aoms/1177732360.