Skip to content

Reporting categorical results that people can check

Give counts and denominators, say which way percentages run, and pair each test with an effect size and interval. A capstone for the track, including Table 1.

Introductory ~10 min10 steps

What runs in CodeSplash

You will be able to

  • Write a sentence with counts, an effect size, an interval and a test
  • Choose the percentage direction that answers your question
  • Report a zero count honestly, and read a Table 1

Read first

01

Counts first

Read

A percentage without a denominator can't be checked. Write 1,198 of 2,691 (44.5%), and your reader can recompute any measure in this track.

Denominators also show how much a percentage can bear. Three of 5 and 600 of 1,000 are both 60%, and they don't carry the same weight.

If some rows are missing, say so, and say whether your denominator includes them.

02

Which way do percentages run?

Predict

Predict first

You want to know whether men and women were admitted at different rates. Which percentages answer that?

The share of each gender who were admittedThe share of admitted applicants who were men
Reveal

The share of each gender who were admitted: 44.5% and 30.4%. The other direction, 1198/(1198+557)≈68%1198 / (1198 + 557) \approx 68\% men among those admitted, depends on how many of each applied. Run percentages within the groups you're comparing.

03

A sentence with everything in it

Read

It names the groups, the counts, the size of the gap, its uncertainty and the test. It also says only "more often": the Simpson's paradox lesson shows why this pooled gap isn't a claim about how departments decided.

04

What's missing?

Reflect

Compare that with a sentence often seen in reports:

Men were significantly more likely to be admitted (p < .001).

List what a reader can't do from this version. Can they tell how big the gap was, how many people it concerns, or which test was run? Can they tell whether anything was adjusted, or how many other comparisons were made?

Find the last result you wrote up. Which of those would a reader have to ask you for?

05

Read a table picture

Read

A mosaic plot shows counts and percentages at once: column widths show one margin, and heights show the shares within each column. Use it when the table is too large for a sentence, and keep the table beside it.

Mosaic plotAre two categorical variables associated — and which cells drive it?
View data
classoutcome
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived
1stSurvived

First 60 of 2201 rows.

For large tables, say what stands out rather than listing every cell, and quote Cramér's V and the standardized residuals that support it.

06

A zero isn't zero risk

Predict

Predict first

Nobody among 25 patients had the side effect. What's the largest true rate still compatible with that? Drag to your guess of the upper 95% limit.

Make your guess between 0 and 0.5 upper limit, then reveal.

Reveal

About 3/25=0.123 / 25 = 0.12, by the rule of three. "0 of 25" is compatible with a rate of around 1 in 8. Report the count together with a Wilson or Clopper–Pearson interval, and never write 0% alone.

07

Table 1

Read
Table 1Recorded · Python and R agreeRecorded 2026-11-17 · 122 values compared
R

Table 1: 4 characteristics of 32 rows by am_f.

Rows
32
q < .05
3

Table 1

CharacteristicOverall (n = 32)automatic (n = 19)manual (n = 13)pqSMDTest
n321913————
mpg, mean (SD)20.09 (6.03)17.15 (3.83)24.39 (6.17).001.003−1.411Welch t-test
hp, mean (SD)146.69 (68.56)160.26 (53.91)126.85 (84.06).221.2210.4732Welch t-test
cyl_f, n (%).013.0171.251χ² test
411 (34.4%)3 (15.8%)8 (61.5%)————
67 (21.9%)4 (21.1%)3 (23.1%)————
814 (43.8%)12 (63.2%)2 (15.4%)————
wt, mean (SD)3.22 (0.98)3.77 (0.78)2.41 (0.62)< .001< .0011.935Welch t-test

Mean (SD) or median [IQR] by the chosen rule; categorical: n (% of non-missing). q: Benjamini–Hochberg (FDR) adjusted across the table.

  • cyl_f: some expected counts are below 5; the χ² p-value is approximate.
  • Tests: Welch t / Welch ANOVA for mean (SD) rows, Wilcoxon rank-sum / Kruskal–Wallis for median [IQR] rows, χ² without continuity correction for categorical rows (Fisher's exact for sparse 2 × 2 tables).
  • In randomized trials, baseline p-values test chance, not imbalance (CONSORT): judge balance by the SMDs (|SMD| > 0.1 is a common flag).
The exact R script · R R version 4.5.1 (2025-06-13)
# Table 1 (characteristics by group)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.table1 1.0.1 · spec b12b2d06635b6ebb
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data (each variable uses its available values; rows without a group are left out)
variables <- c("mpg", "hp", "cyl_f", "wt")
kinds <- c(
  "mpg" = "numeric",
  "hp" = "numeric",
  "cyl_f" = "categorical",
  "wt" = "numeric"
)
level_order <- list(
  "cyl_f" = c("4", "6", "8"),
  "am_f" = c("automatic", "manual")
)
g <- "am_f"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = unique(c(variables, g))))
n_input <- nrow(df)
for (c in names(level_order)) {
  if (is.null(level_order[[c]])) level_order[[c]] <- sort(unique(as.character(df[[c]][!is.na(df[[c]])])), method = "radix")
  df[[c]] <- factor(df[[c]], levels = level_order[[c]])
}
cs_check_finite_columns(df, variables)  # infinite values stop the run (registry/errors.yaml)
warnings <- list()
if (!is.null(g)) {
  df <- df[!is.na(df[[g]]), , drop = FALSE]
  df[[g]] <- droplevels(df[[g]])
  groups <- levels(df[[g]])
  if (length(groups) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = length(groups))
  if (nrow(df) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because the group was missing.", n_input - nrow(df), n_input))
} else {
  groups <- character(0)
}
summary_rule <- "auto"  # auto = mean (SD) unless |G1| >= 1 or values beyond 3 x IQR
do_tests <- TRUE && !is.null(g)
adjust <- "BH"
do_smd <- TRUE && length(groups) == 2
cols <- c("all", groups)
part <- function(v, col) if (col == "all") df[[v]] else df[[v]][df[[g]] == col]

# %% Summaries and tests
values <- list(n_total = nrow(df), n_groups = length(groups), n_vars = length(variables))
for (col in cols) values[[sprintf("n_group[%s]", col)]] <- if (col == "all") nrow(df) else sum(df[[g]] == col)
results <- list()
for (v in variables) {
  res <- list(variable = v, kind = kinds[[v]], p = NULL, statistic = NULL, test = "", smd = NULL)
  if (kinds[[v]] == "numeric") {
    rule <- if (summary_rule == "auto") cs_kim_rule(as.numeric(df[[v]])) else summary_rule
    res$stat <- rule
    cells <- list()
    for (col in cols) {
      x <- as.numeric(part(v, col))
      miss <- sum(is.na(x))
      x <- x[!is.na(x)]
      q <- if (length(x)) unname(quantile(x, c(0.25, 0.5, 0.75), type = 7)) else rep(NaN, 3)
      cc <- list(n = length(x), missing = miss, mean = if (length(x)) mean(x) else NaN, sd = if (length(x) > 1) sd(x) else NaN,
                 median = q[2], q1 = q[1], q3 = q[3])
      cells[[col]] <- cc
      for (k in names(cc)) values[[sprintf("%s[%s|%s]", k, v, col)]] <- cc[[k]]
    }
    res$cells <- cells
    if (do_tests) {
      xs <- lapply(groups, function(col) { x <- as.numeric(part(v, col)); x[!is.na(x)] })
      if (all(vapply(xs, length, 0L) >= 2)) {
        if (rule == "mean_sd" && length(xs) == 2) {
          r <- t.test(xs[[1]], xs[[2]], var.equal = FALSE)  # pinned: Welch
          res$statistic <- unname(r$statistic); res$p <- r$p.value; res$test <- "Welch t-test"
        } else if (rule == "mean_sd") {
          r <- oneway.test(y ~ g, data = data.frame(y = unlist(xs), g = factor(rep(seq_along(xs), lengths(xs)))), var.equal = FALSE)
          res$statistic <- unname(r$statistic); res$p <- r$p.value; res$test <- "Welch ANOVA"
        } else if (length(xs) == 2) {
          r <- wilcox.test(xs[[1]], xs[[2]], exact = FALSE, correct = TRUE)  # pinned: normal approximation, tie-corrected, continuity correction
          res$statistic <- unname(r$statistic); res$p <- r$p.value; res$test <- "Wilcoxon rank-sum"
        } else {
          r <- kruskal.test(xs)
          res$statistic <- unname(r$statistic); res$p <- r$p.value; res$test <- "Kruskal–Wallis"
        }
      }
    }
    if (do_smd) {
      res$smd <- cs_smd_numeric(as.numeric(stats::na.omit(as.numeric(part(v, groups[1])))), as.numeric(stats::na.omit(as.numeric(part(v, groups[2])))))
    }
  } else {
    res$stat <- "n_pct"
    lv <- level_order[[v]]
    cells <- list()
    for (col in cols) {
      s <- part(v, col)
      valid <- sum(!is.na(s))
      counts <- vapply(lv, function(l) sum(s == l, na.rm = TRUE), numeric(1))
      cells[[col]] <- list(valid = valid, missing = sum(is.na(s)), counts = counts)
      values[[sprintf("missing[%s|%s]", v, col)]] <- sum(is.na(s))
      for (i in seq_along(lv)) {
        values[[sprintf("count[%s|%s|%s]", v, lv[i], col)]] <- counts[[i]]
        values[[sprintf("pct[%s|%s|%s]", v, lv[i], col)]] <- if (valid) counts[[i]] / valid else NaN
      }
    }
    res$cells <- cells
    if (do_tests) {
      tab <- sapply(groups, function(col) cells[[col]]$counts)  # levels x groups
      tab <- matrix(tab, nrow = length(lv))
      tab <- tab[rowSums(tab) > 0, colSums(tab) > 0, drop = FALSE]
      if (nrow(tab) >= 2 && ncol(tab) >= 2) {
        expected <- outer(rowSums(tab), colSums(tab)) / sum(tab)
        if (all(dim(tab) == c(2, 2)) && min(expected) < 5) {
          res$p <- fisher.test(tab)$p.value; res$test <- "Fisher's exact"
        } else {
          r <- suppressWarnings(chisq.test(tab, correct = FALSE))  # pinned: no Yates correction
          res$statistic <- unname(r$statistic); res$p <- r$p.value; res$test <- "χ² test"
          if (min(expected) < 5) warnings <- c(warnings, sprintf("%s: some expected counts are below 5; the χ² p-value is approximate.", v))
        }
      }
    }
    if (do_smd) {
      props <- lapply(groups, function(col) { c <- cells[[col]]$counts; if (sum(c)) c / sum(c) else c })
      res$smd <- cs_smd_categorical(props[[1]], props[[2]])
    }
  }
  results[[length(results) + 1]] <- res
}

ps <- vapply(results, function(r) if (is.null(r$p)) NA_real_ else r$p, numeric(1))
qs <- if (do_tests) cs_p_adjust(ps, adjust) else rep(NA_real_, length(results))
for (i in seq_along(results)) {
  results[[i]]["q"] <- list(if (is.na(qs[i])) NULL else qs[i])
  r <- results[[i]]
  v <- r$variable
  values[sprintf("p[%s]", v)] <- list(r$p)
  values[sprintf("q[%s]", v)] <- list(r$q)
  values[sprintf("smd[%s]", v)] <- list(r$smd)
  values[sprintf("statistic[%s]", v)] <- list(r$statistic)
  values[[sprintf("test[%s]", v)]] <- r$test
  values[[sprintf("stat[%s]", v)]] <- r$stat
}
tested <- Filter(function(r) !is.null(r$p), results)
top <- if (length(tested)) tested[[order(vapply(tested, function(r) r$p, 0), vapply(tested, function(r) match(r$variable, variables), 0))[1]]] else NULL
smds <- unlist(lapply(results, function(r) if (!is.null(r$smd) && is.finite(r$smd)) abs(r$smd) else NULL))
adjust_labels <- c(bonferroni = "Bonferroni", holm = "Holm", hochberg = "Hochberg", hommel = "Hommel", BH = "Benjamini–Hochberg (FDR)",
                   BY = "Benjamini–Yekutieli (FDR)", sidak = "Šidák", "holm-sidak" = "Holm–Šidák", none = "none")
values$n_tested <- length(tested)
values$n_significant <- sum(vapply(tested, function(r) !is.null(r$q) && r$q < 0.05, logical(1)))
values$top_variable <- if (is.null(top)) "" else top$variable
values["top_p"] <- list(if (is.null(top)) NULL else top$p)
values["top_q"] <- list(if (is.null(top)) NULL else top$q)
values$adjust_label <- adjust_labels[[adjust]]
values$grouped <- !is.null(g)
values["max_abs_smd"] <- list(if (length(smds)) max(smds) else NULL)

# %% Table 1
fmt <- function(x, d = 2) if (is.null(x) || !is.finite(x)) "—" else sprintf(paste0("%.", d, "f"), x)
show_missing <- TRUE
rows <- list(c(list(characteristic = "n"), stats::setNames(lapply(cols, function(col) as.character(values[[sprintf("n_group[%s]", col)]])), cols)))
for (r in results) {
  v <- r$variable
  base <- list(p = r$p, q = r$q, smd = r$smd, test = r$test)
  if (r$stat == "mean_sd") {
    rows[[length(rows) + 1]] <- c(list(characteristic = sprintf("%s, mean (SD)", v)),
                                  stats::setNames(lapply(cols, function(col) sprintf("%s (%s)", fmt(r$cells[[col]]$mean), fmt(r$cells[[col]]$sd))), cols), base)
  } else if (r$stat == "median_iqr") {
    rows[[length(rows) + 1]] <- c(list(characteristic = sprintf("%s, median [IQR]", v)),
                                  stats::setNames(lapply(cols, function(col) { c <- r$cells[[col]]; sprintf("%s [%s, %s]", fmt(c$median), fmt(c$q1), fmt(c$q3)) }), cols), base)
  } else {
    rows[[length(rows) + 1]] <- c(list(characteristic = sprintf("%s, n (%%)", v)), stats::setNames(as.list(rep("", length(cols))), cols), base)
    lv <- level_order[[v]]
    for (i in seq_along(lv)) {
      rows[[length(rows) + 1]] <- c(list(characteristic = sprintf("    %s", lv[i])), stats::setNames(lapply(cols, function(col) {
        c <- r$cells[[col]]
        sprintf("%d (%s%%)", as.integer(c$counts[[i]]), if (c$valid) fmt(100 * c$counts[[i]] / c$valid, 1) else "—")
      }), cols))
    }
  }
  miss <- vapply(cols, function(col) r$cells[[col]]$missing, numeric(1))
  if (show_missing && any(miss > 0)) {
    rows[[length(rows) + 1]] <- c(list(characteristic = "    (missing)"), stats::setNames(lapply(miss, function(m) as.character(as.integer(m))), cols))
  }
}
columns <- c(list(list(key = "characteristic", label = "Characteristic", type = "string")),
             lapply(cols, function(col) list(key = col, label = sprintf("%s (n = %d)", if (col == "all") "Overall" else col, as.integer(values[[sprintf("n_group[%s]", col)]])), type = "string")),
             if (do_tests) list(list(key = "p", label = "p", type = "pvalue"), list(key = "q", label = "q", type = "pvalue")),
             if (do_smd) list(list(key = "smd", label = "SMD", type = "number")),
             if (do_tests) list(list(key = "test", label = "Test", type = "string")))
cs_publish(list(
  method = "describe.table1",
  methodVersion = "1.0.1",
  title = "Table 1",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = nrow(df),
  summary = paste0(sprintf("Table 1: %d characteristics of %d rows", length(variables), nrow(df)), if (!is.null(g)) sprintf(" by %s.", g) else "."),
  statistics = list(list(key = "n_total", label = "Rows", value = nrow(df)), list(key = "n_significant", label = "q < .05", value = values$n_significant)),
  tables = list(list(key = "table1", title = "Table 1", columns = columns, rows = rows,
                     note = paste0("Mean (SD) or median [IQR] by the chosen rule; categorical: n (% of non-missing). ",
                                   if (do_tests) sprintf("q: %s adjusted across the table.", values$adjust_label) else ""))),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = list(paste("Tests: Welch t / Welch ANOVA for mean (SD) rows, Wilcoxon rank-sum / Kruskal–Wallis for median [IQR] rows,",
                     "χ² without continuity correction for categorical rows (Fisher's exact for sparse 2 × 2 tables)."),
               "In randomized trials, baseline p-values test chance, not imbalance (CONSORT): judge balance by the SMDs (|SMD| > 0.1 is a common flag)."),
  values = values
))
Python

Table 1: 4 characteristics of 32 rows by am_f.

Rows
32
q < .05
3

Table 1

CharacteristicOverall (n = 32)automatic (n = 19)manual (n = 13)pqSMDTest
n321913————
mpg, mean (SD)20.09 (6.03)17.15 (3.83)24.39 (6.17).001.003−1.411Welch t-test
hp, mean (SD)146.69 (68.56)160.26 (53.91)126.85 (84.06).221.2210.4732Welch t-test
cyl_f, n (%).013.0171.251χ² test
411 (34.4%)3 (15.8%)8 (61.5%)————
67 (21.9%)4 (21.1%)3 (23.1%)————
814 (43.8%)12 (63.2%)2 (15.4%)————
wt, mean (SD)3.22 (0.98)3.77 (0.78)2.41 (0.62)< .001< .0011.935Welch t-test

Mean (SD) or median [IQR] by the chosen rule; categorical: n (% of non-missing). q: Benjamini–Hochberg (FDR) adjusted across the table.

  • cyl_f: some expected counts are below 5; the χ² p-value is approximate.
  • Tests: Welch t / Welch ANOVA for mean (SD) rows, Wilcoxon rank-sum / Kruskal–Wallis for median [IQR] rows, χ² without continuity correction for categorical rows (Fisher's exact for sparse 2 × 2 tables).
  • In randomized trials, baseline p-values test chance, not imbalance (CONSORT): judge balance by the SMDs (|SMD| > 0.1 is a common flag).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Table 1 (characteristics by group)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.table1 1.0.1 · spec b12b2d06635b6ebb
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import describe as csd
from codesplash.stats.padjust import LABELS as ADJUST_LABELS, p_adjust

# %% Data (each variable uses its available values; rows without a group are left out)
variables = ["mpg", "hp", "cyl_f", "wt"]
kinds = {"am_f":"categorical","cyl_f":"categorical","hp":"numeric","mpg":"numeric","wt":"numeric"}
level_order = {
    "cyl_f": ["4", "6", "8"],
    "am_f": ["automatic", "manual"],
}
g = "am_f"
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=list(dict.fromkeys(variables + [g])))
n_input = len(df)
for c, lv in level_order.items():
    if not lv:
        lv = level_order[c] = sorted(str(x) for x in df[c].dropna().unique())
    df[c] = pd.Categorical(df[c], categories=lv)
cs.check_finite_columns(df, variables)  # infinite values stop the run (registry/errors.yaml)
warnings = []
if g is not None:
    df = df[df[g].notna()]
    df[g] = df[g].cat.remove_unused_categories()
    groups = [str(x) for x in df[g].cat.categories]
    if len(groups) < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=len(groups))
    if len(df) < n_input:
        warnings.append(f"{n_input - len(df)} of {n_input} rows were left out because the group was missing.")
else:
    groups = []
summary_rule = "auto"  # auto = mean (SD) unless |G1| ≥ 1 or values beyond 3 × IQR
do_tests = True and g is not None
adjust = "BH"
do_smd = True and len(groups) == 2
cols = ["all"] + groups


def part(v, col):
    s = df[v] if col == "all" else df.loc[df[g] == col, v]
    return s


# %% Summaries and tests
values = {"n_total": len(df), "n_groups": len(groups), "n_vars": len(variables)}
for col in cols:
    values[f"n_group[{col}]"] = int(len(df) if col == "all" else (df[g] == col).sum())
results = []  # one per variable
for v in variables:
    res = {"variable": v, "kind": kinds[v], "p": None, "statistic": None, "test": "", "smd": None}
    if kinds[v] == "numeric":
        x_all = df[v].to_numpy(dtype=float)
        rule = csd.kim_rule(x_all) if summary_rule == "auto" else summary_rule
        res["stat"] = rule
        cells = {}
        for col in cols:
            x = part(v, col).to_numpy(dtype=float)
            miss = int(np.isnan(x).sum())
            x = x[~np.isnan(x)]
            q1, med, q3 = (float(q) for q in np.quantile(x, [0.25, 0.5, 0.75])) if x.size else (np.nan,) * 3
            c = {"n": int(x.size), "missing": miss, "mean": float(x.mean()) if x.size else np.nan,
                 "sd": float(x.std(ddof=1)) if x.size > 1 else np.nan, "median": med, "q1": q1, "q3": q3}
            cells[col] = c
            for k, val in c.items():
                values[f"{k}[{v}|{col}]"] = val
        res["cells"] = cells
        if do_tests:
            xs = [part(v, col).dropna().to_numpy(dtype=float) for col in groups]
            if all(x.size >= 2 for x in xs):
                if rule == "mean_sd" and len(xs) == 2:
                    r = stats.ttest_ind(xs[0], xs[1], equal_var=False)  # pinned: Welch
                    res.update(statistic=float(r.statistic), p=float(r.pvalue), test="Welch t-test")
                elif rule == "mean_sd":
                    f, _, _, p = csd.welch_anova(xs)
                    res.update(statistic=f, p=p, test="Welch ANOVA")
                elif len(xs) == 2:
                    r = stats.mannwhitneyu(xs[0], xs[1], alternative="two-sided", method="asymptotic", use_continuity=True)  # pinned: normal approximation, tie-corrected, continuity correction
                    res.update(statistic=float(r.statistic), p=float(r.pvalue), test="Wilcoxon rank-sum")
                else:
                    r = stats.kruskal(*xs)
                    res.update(statistic=float(r.statistic), p=float(r.pvalue), test="Kruskal–Wallis")
        if do_smd:
            res["smd"] = csd.smd_numeric(*[part(v, col).dropna().to_numpy(dtype=float) for col in groups])
    else:
        res["stat"] = "n_pct"
        lv = level_order[v]
        cells = {}
        for col in cols:
            s = part(v, col)
            valid = int(s.notna().sum())
            counts = [int((s == l).sum()) for l in lv]
            cells[col] = {"valid": valid, "missing": int(s.isna().sum()), "counts": counts}
            values[f"missing[{v}|{col}]"] = cells[col]["missing"]
            for l, c in zip(lv, counts):
                values[f"count[{v}|{l}|{col}]"] = c
                values[f"pct[{v}|{l}|{col}]"] = c / valid if valid else np.nan
        res["cells"] = cells
        if do_tests:
            tab = np.array([cells[col]["counts"] for col in groups], dtype=float).T  # levels × groups
            tab = tab[tab.sum(axis=1) > 0][:, tab.sum(axis=0) > 0]
            if tab.shape[0] >= 2 and tab.shape[1] >= 2:
                expected = tab.sum(axis=1, keepdims=True) * tab.sum(axis=0, keepdims=True) / tab.sum()
                if tab.shape == (2, 2) and expected.min() < 5:
                    r = stats.fisher_exact(tab)
                    res.update(statistic=None, p=float(r.pvalue), test="Fisher's exact")
                else:
                    chi2, p, _, _ = stats.chi2_contingency(tab, correction=False)  # pinned: no Yates correction
                    res.update(statistic=float(chi2), p=float(p), test="χ² test")
                    if expected.min() < 5:
                        warnings.append(f"{v}: some expected counts are below 5; the χ² p-value is approximate.")
        if do_smd:
            props = []
            for col in groups:
                c = np.array(cells[col]["counts"], float)
                props.append(c / c.sum() if c.sum() else c)
            res["smd"] = csd.smd_categorical(props[0], props[1])
    results.append(res)

ps = np.array([np.nan if r["p"] is None else r["p"] for r in results])
qs = p_adjust(ps, adjust) if do_tests else np.full(len(results), np.nan)
for r, q in zip(results, qs):
    r["q"] = None if np.isnan(q) else float(q)
    v = r["variable"]
    values.update({f"p[{v}]": r["p"], f"q[{v}]": r["q"], f"smd[{v}]": r["smd"], f"statistic[{v}]": r["statistic"],
                   f"test[{v}]": r["test"], f"stat[{v}]": r["stat"]})
tested = [r for r in results if r["p"] is not None]
# Smallest p first; an undefined (NaN) p sorts last, as R's order() does.
top = min(tested, key=lambda r: (r["p"] if np.isfinite(r["p"]) else np.inf, variables.index(r["variable"]))) if tested else None
values.update({
    "n_tested": len(tested), "n_significant": sum(1 for r in tested if r["q"] is not None and r["q"] < 0.05),
    "top_variable": top["variable"] if top else "", "top_p": top["p"] if top else None, "top_q": top["q"] if top else None,
    "adjust_label": ADJUST_LABELS.get(adjust, adjust), "grouped": g is not None,
    "max_abs_smd": max((abs(r["smd"]) for r in results if r["smd"] is not None and np.isfinite(r["smd"])), default=None),
})


# %% Table 1
def fmt(x, d=2):
    return "—" if x is None or not np.isfinite(x) else f"{x:.{d}f}"


rows = [{"characteristic": "n", **{col: str(values[f"n_group[{col}]"]) for col in cols}}]
for r in results:
    v = r["variable"]
    base = {"p": r["p"], "q": r["q"], "smd": r["smd"], "test": r["test"]}
    if r["stat"] == "mean_sd":
        rows.append({"characteristic": f"{v}, mean (SD)", **{col: f"{fmt(c['mean'])} ({fmt(c['sd'])})" for col, c in r["cells"].items()}, **base})
    elif r["stat"] == "median_iqr":
        rows.append({"characteristic": f"{v}, median [IQR]", **{col: f"{fmt(c['median'])} [{fmt(c['q1'])}, {fmt(c['q3'])}]" for col, c in r["cells"].items()}, **base})
    else:
        rows.append({"characteristic": f"{v}, n (%)", **{col: "" for col in cols}, **base})
        for i, l in enumerate(level_order[v]):
            rows.append({"characteristic": f"    {l}", **{col: f"{c['counts'][i]} ({fmt(100 * c['counts'][i] / c['valid'], 1) if c['valid'] else '—'}%)" for col, c in r["cells"].items()}})
    miss = [r["cells"][col]["missing"] for col in cols]
    if True and any(miss):
        rows.append({"characteristic": "    (missing)", **{col: str(m) for col, m in zip(cols, miss)}})
columns = [{"key": "characteristic", "label": "Characteristic", "type": "string"}]
columns += [{"key": col, "label": ("Overall" if col == "all" else f"{col}") + f" (n = {values[f'n_group[{col}]']})", "type": "string"} for col in cols]
if do_tests:
    columns += [{"key": "p", "label": "p", "type": "pvalue"}, {"key": "q", "label": "q", "type": "pvalue"}]
if do_smd:
    columns.append({"key": "smd", "label": "SMD", "type": "number"})
if do_tests:
    columns.append({"key": "test", "label": "Test", "type": "string"})
cs.publish({
    "method": "describe.table1",
    "methodVersion": "1.0.1",
    "title": "Table 1",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(df),
    "summary": f"Table 1: {len(variables)} characteristics of {len(df)} rows" + (f" by {g}." if g else "."),
    "statistics": [{"key": "n_total", "label": "Rows", "value": len(df)}, {"key": "n_significant", "label": "q < .05", "value": values["n_significant"]}],
    "tables": [{"key": "table1", "title": "Table 1", "columns": columns, "rows": rows,
                "note": "Mean (SD) or median [IQR] by the chosen rule; categorical: n (% of non-missing). "
                        + (f"q: {values['adjust_label']} adjusted across the table." if do_tests else "")}],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": ["Tests: Welch t / Welch ANOVA for mean (SD) rows, Wilcoxon rank-sum / Kruskal–Wallis for median [IQR] rows, "
              "χ² without continuity correction for categorical rows (Fisher's exact for sparse 2 × 2 tables).",
              "In randomized trials, baseline p-values test chance, not imbalance (CONSORT): judge balance by the SMDs (|SMD| > 0.1 is a common flag)."],
    "values": values,
})

A Table 1 describes your groups, here 32 cars in 2 groups: counts and percentages for categories, and means or medians for numbers.

Its p-values are adjusted for multiplicity: 3 of 4 characteristics differ at q < 0.05 after Benjamini–Hochberg (FDR) adjustment. The largest standardized differenceStandardized mean differenceA covariate's group difference in standard deviation units; below about 0.1 usually counts as balanced. is 1.93.

In a randomized trial, any baseline difference is chance by design, so report standardized differences and leave the p-values out.

08

Check your understanding

Checkpoint

Check yourself

30 of 120 patients responded. What percentage is that?

Show the answer

Answer: 25

30 / 120 = 25%. Write "30 of 120 (25%)".

Check yourself

No events occurred among 300 people. What does the rule of three give as an approximate upper 95% limit on the rate?

Show the answer

Answer: 0.01

3 / 300 = 0.01.

Check yourself

Which report of a 3 × 2 table is most useful?

Show the answer

Answer: c

Only the last gives a reader the counts, the pattern, the test and the size of the association.

Check yourself

You sent 200 surveys and 50 people replied; 40 of them said yes. Which report is right?

Show the answer

Answer: b

State the denominator, and be open about who is missing. Non-response can change what the 80% means.

Check yourself

A randomized trial's Table 1 shows p = 0.03 for age. What's the best reading?

Show the answer

Answer: b

Under randomization, the groups come from one population, so that null is true by design. What matters is the size of the imbalance and whether it could affect the result.

Check yourself

A Table 1 shows an absolute standardized difference of 0.35 for age. How would you read it?

Show the answer

Answer: a

Standardized differences are in standard-deviation units, and they don't depend on the sample size, which is why they suit a baseline table.

Check yourself

Why does a Table 1 show missing counts for each characteristic?

Show the answer

Answer: a

A percentage for smoking among 180 people who answered isn't a percentage of all 200. Missingness that differs between groups is a finding in its own right.

09

Do it in CodeSplash

In the app

Every result card writes a summary, plus an APA line with a copy button. Reporting settings on the card sets the p-value style for the project. For a Table 1, choose Characteristics and Groups; you can then set Numeric summary, Multiplicity adjustment (q) and Standardized mean differences (two groups).

Python
import pandas as pd

df = pd.read_csv("ucb_admissions.csv")
print(pd.crosstab(df["gender"], df["admit"], margins=True))
print(pd.crosstab(df["gender"], df["admit"], normalize="index").round(3))
R
table <- margin.table(UCBAdmissions, c(2, 1))
addmargins(table)
round(prop.table(table, 1), 3)
10

Recap

Recap
  • Give counts and denominators, then run percentages within the groups you're comparing.
  • Pair a test with an effect size and interval, and say what the comparison can and can't claim.
  • Report zeros with an upper limit, and don't test baseline rows in a randomized trial.

Concepts in this lesson