EProportions & counts · proportion.gof
Goodness of fit (χ² / G test)
Do the observed category frequencies match expected proportions?
Compares the frequencies of one categorical variable with equal or user-specified proportions using Pearson's χ² or the likelihood-ratio G statistic, with an optional Monte Carlo p-value for small expected counts, per-level residuals and Cohen's w.
A real result
Example “Mendel 9331”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
χ²(3, N = 556) = 0.47, p = .925, w = 0.03
- Pearson χ²
- 0.4700
- G
- 0.4754
- df
- 3
- p (χ² goodness-of-fit test)
- .925
Effect size
- Cohen's w 0.0291 · negligible
Plots
Observed shares with 95% Wilson intervals next to the expected shares.
View data
| Share | series | high | phenotype | low |
|---|---|---|---|---|
| 0.5665 | observed | 0.6071 | round yellow | 0.5250 |
| 0.1942 | observed | 0.2292 | round green | 0.1635 |
| 0.1817 | observed | 0.2159 | wrinkled yellow | 0.1518 |
| 0.0576 | observed | 0.0801 | wrinkled green | 0.0411 |
| 0.5625 | expected | 0.5625 | round yellow | 0.5625 |
| 0.1875 | expected | 0.1875 | round green | 0.1875 |
| 0.1875 | expected | 0.1875 | wrinkled yellow | 0.1875 |
| 0.0625 | expected | 0.0625 | wrinkled green | 0.0625 |
Assumptions
- Expected counts ≥ 5 — Every expected count is at least 5 (smallest 34.75).
Observed and expected frequencies
| phenotype | Observed | Expected | Observed share | Expected share | Pearson residual | Adjusted residual |
|---|---|---|---|---|---|---|
| round yellow | 315 | 312.75 | 0.5665 | 0.5625 | 0.1272 | 0.1924 |
| round green | 108 | 104.25 | 0.1942 | 0.1875 | 0.3673 | 0.4075 |
| wrinkled yellow | 101 | 104.25 | 0.1817 | 0.1875 | −0.3183 | −0.3531 |
| wrinkled green | 32 | 34.750 | 0.0576 | 0.0625 | −0.4665 | −0.4818 |
- Expected proportions: round yellow 0.5625, round green 0.1875, wrinkled yellow 0.1875, wrinkled green 0.0625.
χ²(3, N = 556) = 0.47, p = .925, w = 0.03
- Pearson χ²
- 0.4700
- G
- 0.4754
- df
- 3
- p (χ² goodness-of-fit test)
- .925
Effect size
- Cohen's w 0.0291 · negligible
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Expected counts ≥ 5 — Every expected count is at least 5 (smallest 34.75).
Observed and expected frequencies
| phenotype | Observed | Expected | Observed share | Expected share | Pearson residual | Adjusted residual |
|---|---|---|---|---|---|---|
| round yellow | 315 | 312.75 | 0.5665 | 0.5625 | 0.1272 | 0.1924 |
| round green | 108 | 104.25 | 0.1942 | 0.1875 | 0.3673 | 0.4075 |
| wrinkled yellow | 101 | 104.25 | 0.1817 | 0.1875 | −0.3183 | −0.3531 |
| wrinkled green | 32 | 34.750 | 0.0576 | 0.0625 | −0.4665 | −0.4818 |
- Expected proportions: round yellow 0.5625, round green 0.1875, wrinkled yellow 0.1875, wrinkled green 0.0625.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Mendel 9331mendel_peas · variable: phenotype
- Equal hair eyehair_eye · variable: eye
- Mendel ddof1mendel_peas · variable: phenotype
- Regress ddof too manymendel_peas · variable: phenotype
- Mc g smallmtcars · variable: cyl_f
- Cressie read guidee_guide_gof · variable: category
- Freeman tukey mendelmendel_peas · variable: phenotype
- Neyman monte carloe_guide_gof · variable: category
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Categorical: counts, %, bar chart · Statistics Guide · A — Describe data
- Expected counts ≥ 5? otherwise exact tests · Statistics Guide · E — Compare proportions / frequencies
- Goodness of fit · Statistics Guide · E — Compare proportions / frequencies
What you need
- Variablecategorical / boolean · 1 column · 2–50 levels
- Every stored level is a category, including levels with no rows.
Choices you make
hypothesis
- Expected proportionsdefault equal
The proportions you expect under the null: equal for every level, or your own.
- Equal for every level(default) — Tests whether every level is equally likely; pick it when there's no reason to expect otherwise.
- Custom proportions — Tests against the proportions you enter; pick it when you have known or claimed shares.
- Proportions (in level order)default
One value per level in the stored level order; they are rescaled to sum to 1 (9, 3, 3, 1 works).
- Statisticdefault pearson
Members of the Cressie–Read power-divergence family; all are referred to χ² with k − 1 df.
- Pearson χ² (λ = 1)(default) — The usual χ² statistic.
- Likelihood-ratio G (λ = 0) — Twice the log-likelihood ratio.
- Cressie–Read (λ = 2/3 or your λ) — Cressie and Read's recommended compromise, closest to χ² in small samples.
- Freeman–Tukey (λ = −½) — Least affected by large cells.
- Modified G² (λ = −1) — Undefined when a level has no values.
- Neyman χ² (λ = −2) — Σ (O − E)² / O; undefined when a level has no values.
- λ (Cressie–Read)default 0.6666666666666666
1 gives Pearson's χ², 0 the G statistic, −½ Freeman–Tukey, −2 Neyman.
options
- Parameters estimated from the datadefault 0
How many parameters of the expected distribution you estimated from these data (for example 1 for a fitted Poisson mean). Each lowers the degrees of freedom by one.
- Monte Carlo p-valuedefault off
Simulates the multinomial null (seeded; identical in Python and R). Use when expected counts are small.
- Simulationsdefault 10000
Number of simulated tables behind the Monte Carlo p-value. More is more precise but slower.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Expected counts ≥ 5
Cochran's rule for the χ² approximation; otherwise use the Monte Carlo p-value.
- If violated → Monte Carlo p-value — Simulating the multinomial null does not rely on the χ² approximation, so small expected counts are fine.
Independent observations
What it reports
- Tests: Fit to the expected proportions
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- g
- The mean difference divided by the pooled SD, multiplied by a small-sample correction J that removes Cohen's d's upward bias.
- df
- How much independent information is left to estimate variability after fitting the model.
- p_pearson
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_g
- How surprising your data would be if the null hypothesis were true, as a probability.
- mc_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- cohens_w
- Effect size for chi-square tests. It measures how far the true cell shares sit from the null's.
- min_expected
- The counts a contingency table would have if the variables were independent; χ² needs them not too small.
- statistic_label
- Name of the test used: χ², G or a power-divergence member such as Freeman–Tukey, with (Monte Carlo) when simulated.
- pd_stat
- One family of goodness-of-fit statistics indexed by λ — Pearson's χ² (λ = 1), G² (λ = 0), Freeman–Tukey (−½), Neyman (−2).
- pd_lambda
- One family of goodness-of-fit statistics indexed by λ — Pearson's χ² (λ = 1), G² (λ = 0), Freeman–Tukey (−½), Neyman (−2).
- pd_p
- One family of goodness-of-fit statistics indexed by λ — Pearson's χ² (λ = 1), G² (λ = 0), Freeman–Tukey (−½), Neyman (−2).
Per group, level or term: ddof, observed[<level>], expected[<level>], resid[<level>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Monte Carlo p-values use the shared Wichmann–Hill stream (codesplash.stats.rng ≡ cs_rng), so both engines draw the same tables and agree exactly.
The exact script CodeSplash ran for example “Mendel 9331” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Goodness of fit (χ² / G test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.gof 1.2.0 · spec a06cfefe9986278e
# Dataset: mendel_peas (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import proportions as csp # Monte Carlo p and Wilson intervals (twins of codesplashr)
from codesplash.stats import proportions_ext as csx # power-divergence family (twins of cs_power_divergence …)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mendel_peas.parquet", columns=["phenotype"])
n_input = len(df)
df["phenotype"] = pd.Categorical(df["phenotype"], categories=["round yellow", "round green", "wrinkled yellow", "wrinkled green"]) # stored level order
df = df.dropna(subset=["phenotype"]) # listwise deletion over the analysis columns
df["phenotype"] = df["phenotype"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["phenotype"]) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
v = "phenotype"
levels = ["round yellow", "round green", "wrinkled yellow", "wrinkled green"] # every stored level, including empty ones
values = df[v].astype(str)
observed = np.array([float((values == lv).sum()) for lv in levels])
n, k = float(observed.sum()), len(levels)
probs = np.array([9,3,3,1], dtype=float)
if len(probs) != k:
raise ValueError(f"Give one proportion per level of {v} ({k}: {', '.join(levels)}); got {len(probs)}.")
if probs.sum() <= 0:
raise ValueError("The expected proportions must not all be zero.")
probs = probs / probs.sum() # rescaled to sum to 1 (chisq.test(rescale.p = TRUE))
expected = n * probs
statistic = "pearson"
use_mc = False
ddof = int(0) # Stage 12.7 option: parameters estimated from the data (scipy's ddof)
dof = k - 1 - ddof
if ddof and (dof < 1 or False):
cs.cs_error("CS_E_INVALID_OPTION", option="Estimated parameters", allowed=f"at most {k - 2} with {k} categories, without the Monte Carlo p-value", value=str(ddof))
chi2 = float(np.sum((observed - expected) ** 2 / expected)) # Pearson χ² = scipy.stats.chisquare(observed, expected)
pos = observed > 0
g = float(2 * np.sum(observed[pos] * np.log(observed[pos] / expected[pos]))) # likelihood-ratio G
p_pearson = float(stats.chi2.sf(chi2, dof))
p_g = float(stats.chi2.sf(g, dof))
# Power-divergence statistic (Cressie & Read 1984): Pearson λ = 1, G λ = 0, others below
lam = csx.pd_lambda(statistic, 0.6666666666666666)
pd_stat = chi2 if statistic == "pearson" else (g if statistic == "g" else csx.power_divergence(observed, expected, lam))
pd_p = float(stats.chi2.sf(pd_stat, dof)) if math.isfinite(pd_stat) else None
if pd_p is None:
warnings.append(f"The {csx.PD_LABEL[statistic]} statistic is undefined when a level has no values; Pearson's χ² is used instead.")
statistic, lam, pd_stat, pd_p = "pearson", 1.0, chi2, p_pearson
if not use_mc:
mc_p = None
elif statistic in ("pearson", "g"):
mc_p = csp.gof_mc(observed, probs, int(10000), seed=42, statistic=statistic)
else:
mc_p = csx.pd_gof_mc(observed, probs, int(10000), 42, lam)
p = mc_p if use_mc else pd_p
label = ("G test" if statistic == "g" else "χ² goodness-of-fit test" if statistic == "pearson" else f"{csx.PD_LABEL[statistic]} goodness-of-fit test") + (" (Monte Carlo)" if use_mc else "")
w = math.sqrt(chi2 / n) # Cohen's w
resid = (observed - expected) / np.sqrt(expected) # Pearson residuals
stdres = (observed - expected) / np.sqrt(expected * (1 - probs)) # adjusted residuals (chisq.test()$stdres)
min_expected = float(expected.min())
# %% Assumptions
below = int((expected < 5).sum())
if use_mc:
status, detail = "info", f"Monte Carlo p-value ({int(10000):,} simulations, seed 42); smallest expected count {min_expected:.2f}."
elif min_expected < 1:
status, detail = "fail", f"Smallest expected count {min_expected:.2f} (< 1): the χ² approximation fails; use the Monte Carlo p-value."
elif below:
status, detail = "warn", f"{below} of {k} expected counts are below 5 (smallest {min_expected:.2f}); consider the Monte Carlo p-value."
else:
status, detail = "pass", f"Every expected count is at least 5 (smallest {min_expected:.2f})."
assumptions = [{"key": "expected_counts", "label": "Expected counts ≥ 5", "status": status, "detail": detail}]
# %% Result
size = magnitude(w, (0.1, 0.3, 0.5))
summary = f"{label} on {int(n)} values of {v} over {k} levels: {cs.fmt_p(p)}; Cohen's w = {w:.2f} ({size})."
result_values = {"n": int(n), "k": k, "chi2": chi2, "g": g, "df": float(dof), "p_pearson": p_pearson, "p_g": p_g, "mc_p": mc_p, "p": p,
"cohens_w": w, "min_expected": min_expected, "statistic_label": label, "pd_stat": pd_stat, "pd_lambda": lam, "pd_p": pd_p, **({"ddof": ddof} if ddof else {})}
rows = []
props = observed / n
for i, lv in enumerate(levels):
lo, hi = csp.prop_ci(observed[i], n, 0.95, "wilson")
rows.append({"level": lv, "observed": int(observed[i]), "expected": float(expected[i]), "proportion": float(props[i]),
"expected_prop": float(probs[i]), "resid": float(resid[i]), "stdres": float(stdres[i]), "ci_low": lo, "ci_high": hi})
result_values[f"observed[{lv}]"] = float(observed[i])
result_values[f"expected[{lv}]"] = float(expected[i])
result_values[f"resid[{lv}]"] = float(resid[i])
cs.publish({
"method": "proportion.gof",
"methodVersion": "1.2.0",
"title": "Goodness of fit",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(n),
"summary": summary,
"apa": (f"{'G' if statistic == 'g' else 'χ²'}({dof}, N = {int(n)}) = {cs.fmt_num(g if statistic == 'g' else chi2)}, {cs.fmt_p(p)}, w = {cs.fmt_num(w)}"
if statistic in ("pearson", "g") else
f"{csx.PD_LABEL[statistic]} (λ = {cs.fmt_num(lam)})({dof}, N = {int(n)}) = {cs.fmt_num(pd_stat)}, {cs.fmt_p(p)}, w = {cs.fmt_num(w)}"),
"statistics": [
{"key": "chi2", "label": "Pearson χ²", "value": chi2}, {"key": "g", "label": "G", "value": g},
{"key": "df", "label": "df", "value": dof}, {"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
] + ([{"key": "pd_stat", "label": f"{csx.PD_LABEL[statistic]} (λ = {lam:.3g})", "value": pd_stat},
{"key": "pd_p", "label": f"p ({csx.PD_LABEL[statistic]})", "value": pd_p, "format": "p"}] if statistic not in ("pearson", "g") else []),
"tables": [{
"key": "frequencies", "title": "Observed and expected frequencies",
"columns": [{"key": "level", "label": v, "type": "string"}, {"key": "observed", "label": "Observed", "type": "integer"},
{"key": "expected", "label": "Expected", "type": "number"}, {"key": "proportion", "label": "Observed share", "type": "number"},
{"key": "expected_prop", "label": "Expected share", "type": "number"},
{"key": "resid", "label": "Pearson residual", "type": "number"}, {"key": "stdres", "label": "Adjusted residual", "type": "number"}],
"rows": rows,
}],
"effectSizes": [{"key": "cohens_w", "label": "Cohen's w", "value": w, "method": "√(χ² / n)", "magnitude": size, "ruleSet": "Cohen (1988)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": ["Expected proportions: " + ", ".join(f"{lv} {pr:.4g}" for lv, pr in zip(levels, probs)) + "."],
"charts": [cs.chart(
"shares", "forest", f"Observed vs expected shares of {v}",
{"label": cs.col(v, [r["level"] for r in rows] * 2),
"estimate": cs.col("Share", [r["proportion"] for r in rows] + [r["expected_prop"] for r in rows]),
"low": cs.col("low", [r["ci_low"] for r in rows] + [r["expected_prop"] for r in rows]),
"high": cs.col("high", [r["ci_high"] for r in rows] + [r["expected_prop"] for r in rows]),
"group": cs.col("series", ["observed"] * k + ["expected"] * k)},
note="Observed shares with 95% Wilson intervals next to the expected shares.",
)],
"values": result_values,
})
The exact script CodeSplash ran for example “Mendel 9331” · R version 4.5.1 (2025-06-13)
# Goodness of fit (χ² / G test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.gof 1.2.0 · spec a06cfefe9986278e
# Dataset: mendel_peas (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_gof_mc, cs_prop_ci, cs_power_divergence (twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mendel_peas.parquet", col_select = c("phenotype")))
n_input <- nrow(df)
df[["phenotype"]] <- factor(df[["phenotype"]], levels = c("round yellow", "round green", "wrinkled yellow", "wrinkled green")) # stored level order
df <- df[stats::complete.cases(df[c("phenotype")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("phenotype")) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
v <- "phenotype"
levels_v <- c("round yellow", "round green", "wrinkled yellow", "wrinkled green") # every stored level, including empty ones
observed <- vapply(levels_v, function(lv) sum(as.character(df[[v]]) == lv), numeric(1))
n <- sum(observed)
k <- length(levels_v)
probs <- c(9, 3, 3, 1)
if (length(probs) != k) stop(sprintf("Give one proportion per level of %s (%d: %s); got %d.", v, k, paste(levels_v, collapse = ", "), length(probs)))
if (sum(probs) <= 0) stop("The expected proportions must not all be zero.")
probs <- probs / sum(probs) # rescaled to sum to 1 (chisq.test(rescale.p = TRUE))
expected <- n * probs
statistic <- "pearson"
use_mc <- FALSE
ddof <- as.integer(0) # Stage 12.7 option: parameters estimated from the data (scipy's ddof)
dof <- k - 1 - ddof
if (ddof > 0 && (dof < 1 || FALSE)) {
cs_error("CS_E_INVALID_OPTION", option = "Estimated parameters", allowed = sprintf("at most %d with %d categories, without the Monte Carlo p-value", k - 2, k), value = as.character(ddof))
}
chi2 <- sum((observed - expected)^2 / expected) # Pearson χ² = chisq.test(observed, p = probs)$statistic
pos <- observed > 0
g <- 2 * sum(observed[pos] * log(observed[pos] / expected[pos])) # likelihood-ratio G
p_pearson <- pchisq(chi2, dof, lower.tail = FALSE)
p_g <- pchisq(g, dof, lower.tail = FALSE)
# Power-divergence statistic (Cressie & Read 1984): Pearson lambda = 1, G lambda = 0, others below
pd_label <- c(pearson = "Pearson χ²", g = "likelihood-ratio G²", cressie_read = "Cressie–Read", freeman_tukey = "Freeman–Tukey",
mod_g = "modified G²", neyman = "Neyman χ²")
lam <- cs_pd_lambda(statistic, 0.6666666666666666)
pd_stat <- if (statistic == "pearson") chi2 else if (statistic == "g") g else cs_power_divergence(observed, expected, lam)
pd_p <- if (is.finite(pd_stat)) pchisq(pd_stat, dof, lower.tail = FALSE) else NULL
if (is.null(pd_p)) {
warnings <- c(warnings, sprintf("The %s statistic is undefined when a level has no values; Pearson's χ² is used instead.", pd_label[[statistic]]))
statistic <- "pearson"; lam <- 1; pd_stat <- chi2; pd_p <- p_pearson
}
mc_p <- if (!use_mc) {
NULL
} else if (statistic %in% c("pearson", "g")) {
cs_gof_mc(observed, probs, 10000, seed = 42, statistic = statistic)
} else {
cs_pd_gof_mc(observed, probs, 10000, 42, lam)
}
p <- if (use_mc) mc_p else pd_p
label <- paste0(if (statistic == "g") "G test" else if (statistic == "pearson") "χ² goodness-of-fit test" else paste(pd_label[[statistic]], "goodness-of-fit test"),
if (use_mc) " (Monte Carlo)" else "")
w <- sqrt(chi2 / n) # Cohen's w
resid <- (observed - expected) / sqrt(expected) # Pearson residuals
stdres <- (observed - expected) / sqrt(expected * (1 - probs)) # adjusted residuals (chisq.test()$stdres)
min_expected <- min(expected)
# %% Assumptions
below <- sum(expected < 5)
if (use_mc) {
status <- "info"
detail <- sprintf("Monte Carlo p-value (%s simulations, seed 42); smallest expected count %.2f.",
format(10000, big.mark = ","), min_expected)
} else if (min_expected < 1) {
status <- "fail"
detail <- sprintf("Smallest expected count %.2f (< 1): the χ² approximation fails; use the Monte Carlo p-value.", min_expected)
} else if (below > 0) {
status <- "warn"
detail <- sprintf("%d of %d expected counts are below 5 (smallest %.2f); consider the Monte Carlo p-value.", below, k, min_expected)
} else {
status <- "pass"
detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", min_expected)
}
assumptions <- list(list(key = "expected_counts", label = "Expected counts ≥ 5", status = status, detail = detail))
# %% Result
size <- magnitude(w, c(0.1, 0.3, 0.5))
summary <- sprintf("%s on %d values of %s over %d levels: %s; Cohen's w = %.2f (%s).", label, as.integer(n), v, k, cs_fmt_p(p), w, size)
result_values <- list(n = n, k = k, chi2 = chi2, g = g, df = dof, p_pearson = p_pearson, p_g = p_g, mc_p = mc_p, p = p,
cohens_w = w, min_expected = min_expected, statistic_label = label, pd_stat = pd_stat, pd_lambda = lam, pd_p = pd_p)
if (ddof > 0) result_values$ddof <- ddof
props <- observed / n
cis <- lapply(seq_len(k), function(i) cs_prop_ci(observed[[i]], n, 0.95, "wilson"))
rows <- data.frame(level = levels_v, observed = as.integer(observed), expected = expected, proportion = props, expected_prop = probs,
resid = resid, stdres = stdres, ci_low = vapply(cis, `[`, numeric(1), 1), ci_high = vapply(cis, `[`, numeric(1), 2),
row.names = NULL)
for (i in seq_len(k)) {
result_values[[sprintf("observed[%s]", levels_v[i])]] <- observed[[i]]
result_values[[sprintf("expected[%s]", levels_v[i])]] <- expected[[i]]
result_values[[sprintf("resid[%s]", levels_v[i])]] <- resid[[i]]
}
cs_publish(list(
method = "proportion.gof",
methodVersion = "1.2.0",
title = "Goodness of fit",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = if (statistic %in% c("pearson", "g")) {
sprintf("%s(%d, N = %d) = %s, %s, w = %s", if (statistic == "g") "G" else "χ²", dof, as.integer(n),
cs_fmt_num(if (statistic == "g") g else chi2), cs_fmt_p(p), cs_fmt_num(w))
} else {
sprintf("%s (λ = %s)(%d, N = %d) = %s, %s, w = %s", pd_label[[statistic]], cs_fmt_num(lam), as.integer(dof), as.integer(n),
cs_fmt_num(pd_stat), cs_fmt_p(p), cs_fmt_num(w))
},
statistics = c(list(
list(key = "chi2", label = "Pearson χ²", value = chi2), list(key = "g", label = "G", value = g),
list(key = "df", label = "df", value = dof), list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p")),
if (!statistic %in% c("pearson", "g")) list(
list(key = "pd_stat", label = sprintf("%s (λ = %s)", pd_label[[statistic]], format(signif(lam, 3))), value = pd_stat),
list(key = "pd_p", label = sprintf("p (%s)", pd_label[[statistic]]), value = pd_p, format = "p"))
),
tables = list(list(
key = "frequencies", title = "Observed and expected frequencies",
columns = list(
list(key = "level", label = v, type = "string"), list(key = "observed", label = "Observed", type = "integer"),
list(key = "expected", label = "Expected", type = "number"), list(key = "proportion", label = "Observed share", type = "number"),
list(key = "expected_prop", label = "Expected share", type = "number"),
list(key = "resid", label = "Pearson residual", type = "number"), list(key = "stdres", label = "Adjusted residual", type = "number")
),
rows = rows[, c("level", "observed", "expected", "proportion", "expected_prop", "resid", "stdres")]
)),
effectSizes = list(list(key = "cohens_w", label = "Cohen's w", value = w, method = "√(χ² / n)", magnitude = size, ruleSet = "Cohen (1988)")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0("Expected proportions: ", paste(sprintf("%s %s", levels_v, format(signif(probs, 4))), collapse = ", "), ".")),
charts = list(cs_chart(
"shares", "forest", sprintf("Observed vs expected shares of %s", v),
list(label = cs_col(v, rep(levels_v, 2)), estimate = cs_col("Share", c(rows$proportion, rows$expected_prop)),
low = cs_col("low", c(rows$ci_low, rows$expected_prop)), high = cs_col("high", c(rows$ci_high, rows$expected_prop)),
group = cs_col("series", rep(c("observed", "expected"), each = k))),
note = "Observed shares with 95% Wilson intervals next to the expected shares."
)),
values = result_values
))
Sources
- Cochran, W. G. (1954). Some methods for strengthening the common χ² tests. Biometrics, 10, 417–451.
- Agresti, A. (2013). Categorical Data Analysis (3rd ed.). Wiley.
- Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.).
From the CodeSplash method registry · proportion.gof v1.2.0.