ADescribe · describe.table1
Table 1 (characteristics by group)
How do the groups compare on their baseline characteristics?
The classic "Table 1": mean (SD) or median [IQR] for numeric variables (chosen per variable by skewness and far-out values, or fixed), n (%) per level for categorical ones, missing counts, and — by group — p-values (Welch t/ANOVA, Wilcoxon/Kruskal–Wallis, χ²/Fisher) with multiplicity-adjusted q-values and standardized mean differences.
A real result
Example “Mtcars by transmission”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Table 1: 4 characteristics of 32 rows by am_f.
- Rows
- 32
- q < .05
- 3
Table 1
| Characteristic | Overall (n = 32) | automatic (n = 19) | manual (n = 13) | p | q | SMD | Test |
|---|---|---|---|---|---|---|---|
| n | 32 | 19 | 13 | — | — | — | — |
| mpg, mean (SD) | 20.09 (6.03) | 17.15 (3.83) | 24.39 (6.17) | .001 | .003 | −1.411 | Welch t-test |
| hp, mean (SD) | 146.69 (68.56) | 160.26 (53.91) | 126.85 (84.06) | .221 | .221 | 0.4732 | Welch t-test |
| cyl_f, n (%) | .013 | .017 | 1.251 | χ² test | |||
| 4 | 11 (34.4%) | 3 (15.8%) | 8 (61.5%) | — | — | — | — |
| 6 | 7 (21.9%) | 4 (21.1%) | 3 (23.1%) | — | — | — | — |
| 8 | 14 (43.8%) | 12 (63.2%) | 2 (15.4%) | — | — | — | — |
| wt, mean (SD) | 3.22 (0.98) | 3.77 (0.78) | 2.41 (0.62) | < .001 | < .001 | 1.935 | Welch 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).
Table 1: 4 characteristics of 32 rows by am_f.
- Rows
- 32
- q < .05
- 3
Table 1
| Characteristic | Overall (n = 32) | automatic (n = 19) | manual (n = 13) | p | q | SMD | Test |
|---|---|---|---|---|---|---|---|
| n | 32 | 19 | 13 | — | — | — | — |
| mpg, mean (SD) | 20.09 (6.03) | 17.15 (3.83) | 24.39 (6.17) | .001 | .003 | −1.411 | Welch t-test |
| hp, mean (SD) | 146.69 (68.56) | 160.26 (53.91) | 126.85 (84.06) | .221 | .221 | 0.4732 | Welch t-test |
| cyl_f, n (%) | .013 | .017 | 1.251 | χ² test | |||
| 4 | 11 (34.4%) | 3 (15.8%) | 8 (61.5%) | — | — | — | — |
| 6 | 7 (21.9%) | 4 (21.1%) | 3 (23.1%) | — | — | — | — |
| 8 | 14 (43.8%) | 12 (63.2%) | 2 (15.4%) | — | — | — | — |
| wt, mean (SD) | 3.22 (0.98) | 3.77 (0.78) | 2.41 (0.62) | < .001 | < .001 | 1.935 | Welch 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).
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
- Mtcars by transmissionmtcars · group: am_f · variables: mpg, hp, cyl_f, wt
- Survey by sex missings1_survey · group: sex · variables: height, pulse rate, smoke, exercise, writing_hand
- Iris three groups medianiris · group: Species · variables: Sepal.Length, Petal.Width
- Ungroupeds1_survey · variables: age, clap
- Sparse fishers1_outliers · group: arm · variables: event, reading
- Survey three groupss1_survey · group: clap · variables: writing_hand, fold, age
- Degenerate infmtcars · group: am_f · variables: mpg, hp, cyl_f, wt
- Degenerate n2mtcars · group: am_f · variables: mpg, hp, cyl_f, wt
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Explore: summary statistics, plots, outliers, skewness · Statistics Guide · Step 0 — Prepare your data
- Continuous: mean, median, SD, IQR · Statistics Guide · A — Describe data
- Categorical: counts, %, bar chart · Statistics Guide · A — Describe data
- Multiple comparisons · Statistics Guide · Additional considerations
- Descriptive statistics (mean, median, percentiles) · DS & ML Decision Guide · Describe — summarize and visualize
What you need
- Characteristicsnumeric / categorical / boolean · 1–40 columns
- Numeric and categorical variables to summarize.
- Groupscategorical / boolean · 0–1 column · 2–10 levels
- Optional — one column per group, with tests and SMDs.
- Always median [IQR]numeric · 0–40 columns
- Numeric characteristics shown as median [IQR] with rank tests, whatever the numeric summary says. Added to the table if not already a characteristic.
Choices you make
statistics
- Numeric summarydefault auto
Automatic uses mean (SD) when |skewness| < 1 and no value lies beyond 3 × IQR from the quartiles, else median [IQR].
- Automatic: mean (SD) unless skewed(default) — Uses mean (SD) unless a variable is skewed, then median [IQR]; the usual choice.
- Mean (SD) — Reports mean (SD) for all numbers; pick it for roughly symmetric variables.
- Median [IQR] — Reports median [IQR] for all numbers; pick it for skewed variables.
- Standardized mean differencesdefault on
Show standardized mean differences between groups: a size-of-difference measure that doesn't depend on n. Two groups by default; see the next option for more.
- SMD with three or more groupsdefault none
With three or more groups there is one SMD per pair of groups. Summarize them by their mean or their largest value; two groups are unchanged.
- None (two groups only)(default) — Shows standardized differences only when there are exactly two groups, as before.
- Mean of the pairwise SMDs — Averages the absolute SMD over every pair of groups, as R's tableone does; a summary of overall imbalance.
- Largest pairwise SMD — Shows the largest absolute SMD between any two groups; flags the worst-balanced pair.
hypothesis
- Test for differences between groupsdefault on
Add a p-value per variable comparing groups (descriptive only; not a substitute for a planned analysis).
- Multiplicity adjustment (q)default BH
How p-values are corrected for making several comparisons. Holm limits any false alarm; BH limits the share of false discoveries.
- Benjamini–Hochberg (FDR)(default) — Controls the expected share of false positives among the findings; pick it when screening many comparisons.
- Holm (FWER) — Controls the chance of any false positive and always finds at least as much as Bonferroni; a good default.
- None — Reports raw p-values; use it for one planned comparison, or say plainly that the results are exploratory.
options
- Show missing countsdefault on
Show how many values are missing for each variable.
- Two-level characteristicsdefault all_levels
How to show a categorical characteristic with exactly two levels: a row per level, or one row for the second level.
- Every level(default) — Shows a row for each level, as for any categorical characteristic.
- One row (second level) — Shows one row with the second level's n (%), such as "smoker = yes"; the usual journal layout.
- Show the Overall columndefault on
Show a column for all rows next to the groups. Without groups the Overall column always shows.
What it reports
- n_total
- How many independent units the analysis used; it sets precision and power.
- n_groups
- How many independent units the analysis used; it sets precision and power.
- n_vars
- How many independent units the analysis used; it sets precision and power.
- n_tested
- How many independent units the analysis used; it sets precision and power.
- n_significant
- How many independent units the analysis used; it sets precision and power.
- top_variable
- The characteristic with the smallest between-group p-value. Empty when no tests were run.
- top_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- top_q
- Adjusted p-value (q) of the characteristic with the smallest p, corrected across the table. Empty when no tests were run.
- adjust_label
- Running many tests raises the chance that at least one is a false positive.
- grouped
- True when a group column splits the table, so between-group tests can run; false for an overall summary.
- max_abs_smd
- A covariate's group difference in standard deviation units; below about 0.1 usually counts as balanced.
Per group, level or term: n_group[<group> or all], n[<variable>|<group>], missing[…], mean[…], sd[…], median[…], q1[…], q3[…], count[<variable>|<level>|<group>], pct[…], p[<variable>], q[…], smd[…], statistic[…], test[…], stat[…], smd_mean[<variable>], smd_max[<variable>], shown_level[<variable>], table_rows, table_columns
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
- Welch ANOVA: codesplash.stats.describe.welch_anova (closed form) ↔ oneway.test(var.equal = FALSE).
- Rank tests are pinned to the normal approximation with tie and continuity corrections (scipy method='asymptotic' ↔ exact = FALSE, correct = TRUE).
The exact script CodeSplash ran for example “Mtcars by transmission” · 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,
})
The exact script CodeSplash ran for example “Mtcars by transmission” · 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
))
Sources
- Hayes-Larson, E., Kezios, K. L., Mooney, S. J., & Lovasi, G. (2019). Who is in this study, anyway? Guidelines for a useful Table 1. Journal of Clinical Epidemiology, 114, 125–132.
- Yang, D., & Dalton, J. E. (2012). A unified approach to measuring the effect size between two groups using SAS. SAS Global Forum, paper 335.
- Moher, D., et al. (2010). CONSORT 2010 explanation and elaboration. BMJ, 340, c869 (baseline significance tests).
- Yoshida, K., & Bartel, A. tableone: Create 'Table 1' to describe baseline characteristics (R package; the mean of pairwise SMDs for three or more groups).
From the CodeSplash method registry · describe.table1 v1.1.0.