Table 1
Build the standard table of baseline characteristics by group, read standardized differences with two groups or more, and know when p-values don't belong in it.
What runs in CodeSplash
- Table 1 (characteristics by group) Verified in Python and R
You will be able to
- Build a Table 1 by group
- Read a standardized mean difference
- Explain why p-values in a randomized trial's Table 1 mislead
- Choose how standardized differences show with three or more groups
What a Table 1 is for
ReadA Table 1Table 1The first table in many papers. It describes who is in each group, using summaries by variable, and how much is missing. is the first table in many papers. It describes who or what is in each group: mean (SD) or median [IQR] for numbers, n (%) for categories, and how much is missing.
It answers two questions. Who is this study about? And do the groups differ in ways that could explain the result?
Run one
In the appHere are 32 cars compared across 2 transmission types.
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).
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
))
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).
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,
})
CodeSplash chooses mean (SD) or median [IQR] for each variable from its skew and far-out values, unless you fix one. It also gives a standardized difference and a test for each row.
Standardized differences
ReadA p-value depends on sample size. To compare balance across studies, use the standardized mean differenceStandardized mean differenceA covariate's group difference in standard deviation units; below about 0.1 usually counts as balanced.:
An absolute SMD above 0.1 is a common flag for imbalance. In this table the largest is 1.93. These groups are nowhere near balanced.
Should a trial report p-values here?
PredictPredict first
In a randomized trial, a Table 1 shows a p-value below 0.05 for baseline age. Does that p-value tell you randomization failed?
Reveal
The answer: No, any differences are chance by construction
No. In a proper trial, any baseline difference arises by chance, and p-values there test a null you know is true. About 5% of rows will fall below 0.05 regardless. Judge imbalance by its size. It matters when a variable strongly predicts the outcome, and then you adjust for it.
See balance by chance
ExploreRandomize small groups repeatedly and watch how much baseline differences swing.
DExplorable · What randomization balances
Does randomizing guarantee the groups match, and does it reach what you never measured?
In what share of assignments will the groups differ by more than 0.1 SD on the measured covariate?
Who gets treated
Commit your prediction above to see the result
Make your prediction to see the result.
Observational studies are different
ReadWithout randomization, imbalance is a warning about confounding. Age may differ because older patients get a different treatment, and any outcome difference may be about age.
This table's p-values are adjusted with Benjamini–Hochberg (FDR) across 4 tests. Treat them as description. To adjust for confounding, use the Causal studio.
Three groups or more
In the appA standardized difference compares two groups. With three or more, SMD with three or more groups chooses what the table shows: None (two groups only), the default, or Mean of the pairwise SMDs, as R's tableone does, or Largest pairwise SMD, which flags the worst-balanced pair.
Three more options shape the table for a journal. Always median [IQR] fixes the summary for the columns you list. Two-level characteristics can show One row (second level), such as "smoker = yes". Show the Overall column adds a column for all rows.
When the tests come off
ReflectTest for differences between groups is on by default in Analyze, and you can turn it off. In Guided, the Share step starts Table 1 without tests when you've said the groups were assigned at random, for the reason in the prediction above.
The same table is also the citable end of a comparison. On Insights' Compare, Test these differences in Analyze opens Table 1 with one column for each side.
Think of a Table 1 you've read recently. Did its p-values change what you believed about the groups?
A quick Table 1 in Insights
In the appThe Statistician page in Insights has a Table 1 section. Pick the groups, choose whether to show Tests between groups, and press Quick run. A quick run isn't saved and doesn't enter the ledger, so use it to look. Open in Analyze sets up the same table as an analysis you can keep and cite.
Check your understanding
CheckpointCheck yourself
Group means are 55 and 50, with a pooled SD of 10. What is the standardized mean difference?
Show the answer
Answer: 0.5
(55 − 50) / 10. That's well above the common 0.1 flag.
Check yourself
Why report SMDs rather than p-values for baseline balance?
Show the answer
Answer: a
With a large sample a trivial imbalance gets a tiny p-value, and with a small one a big imbalance can look fine. The SMD reports the size either way.
Check yourself
What belongs in a Table 1 for a skewed variable such as hospital length of stay?
Show the answer
Answer: b
Skew makes the mean and SD hard to read. CodeSplash picks median [IQR] automatically for skewed columns unless you fix the choice.
Check yourself
A Table 1 compares four sites. You want one number per row that warns you when any two sites are badly out of balance. Which setting gives it?
Show the answer
Answer: c
The largest pairwise SMD is the worst pair, so one badly balanced pair can't hide behind well-balanced ones. The mean summarizes overall imbalance and can dilute it.
Recap
Recap- A Table 1 describes who is in each group.
- Judge balance by standardized differences, not p-values.
- In a randomized trial, baseline p-values test a null you already know is true.
Concepts in this lesson