Skip to content

Table 1 for readers

Turn the baseline table into something a reader can use. Decide which columns stay, label every number, and write the two sentences that go with it.

Applied ~10 min10 steps

What runs in CodeSplash

You will be able to

  • Choose which columns a Table 1 needs for its design
  • Make every row readable, with group sizes, labels and missing counts
  • Write the short passage that goes with a Table 1

Read first

01

What your reader wants from it

Read

You built a Table 1Table 1The first table in many papers. It describes who is in each group, using summaries by variable, and how much is missing. in Describe and Explore. Now look at it from the reader's side. They come with two questions:

  • Who is this about? Does it apply to the people I care about?
  • Could something else explain the result? Do the groups differ in ways that matter?

A row earns its place by helping with one of those. If it doesn't, cut it. It can go in an appendix.

02

Build one

In the app

Here are 5 characteristics of 236 survey respondents, by sex.

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

Table 1: 5 characteristics of 236 rows by sex.

Rows
236
q < .05
1

Table 1

CharacteristicOverall (n = 236)Female (n = 118)Male (n = 118)pqSMDTest
n236118118————
height, mean (SD)172.38 (9.87)165.69 (6.15)178.83 (8.38)< .001< .001−1.787Welch t-test
(missing)281612————
pulse rate, mean (SD)74.16 (11.72)75.13 (11.41)73.20 (12.00).256.3920.1647Welch t-test
(missing)452322————
smoke, n (%).314.3920.2476χ² test
Never188 (80.0%)99 (83.9%)89 (76.1%)————
Occas19 (8.1%)9 (7.6%)10 (8.5%)————
Regul17 (7.2%)5 (4.2%)12 (10.3%)————
Heavy11 (4.7%)5 (4.2%)6 (5.1%)————
(missing)101————
exercise, n (%).057.1430.3152χ² test
None24 (10.2%)11 (9.3%)13 (11.0%)————
Some98 (41.5%)58 (49.2%)40 (33.9%)————
Freq114 (48.3%)49 (41.5%)65 (55.1%)————
writing_hand, n (%).461.4610.0963χ² test
Left17 (7.2%)7 (6.0%)10 (8.5%)————
Right218 (92.8%)110 (94.0%)108 (91.5%)————
(missing)110————

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

  • 1 of 237 rows were left out because the group was missing.
  • 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 d79ddb60b60eff07
# Dataset: s1_survey (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("height", "pulse rate", "smoke", "exercise", "writing_hand")
kinds <- c(
  "height" = "numeric",
  "pulse rate" = "numeric",
  "smoke" = "categorical",
  "exercise" = "categorical",
  "writing_hand" = "categorical"
)
level_order <- list(
  "smoke" = c("Never", "Occas", "Regul", "Heavy"),
  "exercise" = c("None", "Some", "Freq"),
  "writing_hand" = c("Left", "Right"),
  "sex" = c("Female", "Male")
)
g <- "sex"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_survey.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: 5 characteristics of 236 rows by sex.

Rows
236
q < .05
1

Table 1

CharacteristicOverall (n = 236)Female (n = 118)Male (n = 118)pqSMDTest
n236118118————
height, mean (SD)172.38 (9.87)165.69 (6.15)178.83 (8.38)< .001< .001−1.787Welch t-test
(missing)281612————
pulse rate, mean (SD)74.16 (11.72)75.13 (11.41)73.20 (12.00).256.3920.1647Welch t-test
(missing)452322————
smoke, n (%).314.3920.2476χ² test
Never188 (80.0%)99 (83.9%)89 (76.1%)————
Occas19 (8.1%)9 (7.6%)10 (8.5%)————
Regul17 (7.2%)5 (4.2%)12 (10.3%)————
Heavy11 (4.7%)5 (4.2%)6 (5.1%)————
(missing)101————
exercise, n (%).057.1430.3152χ² test
None24 (10.2%)11 (9.3%)13 (11.0%)————
Some98 (41.5%)58 (49.2%)40 (33.9%)————
Freq114 (48.3%)49 (41.5%)65 (55.1%)————
writing_hand, n (%).461.4610.0963χ² test
Left17 (7.2%)7 (6.0%)10 (8.5%)————
Right218 (92.8%)110 (94.0%)108 (91.5%)————
(missing)110————

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

  • 1 of 237 rows were left out because the group was missing.
  • 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 d79ddb60b60eff07
# Dataset: s1_survey (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 = ["height", "pulse rate", "smoke", "exercise", "writing_hand"]
kinds = {"exercise":"categorical","height":"numeric","pulse rate":"numeric","sex":"categorical","smoke":"categorical","writing_hand":"categorical"}
level_order = {
    "smoke": ["Never", "Occas", "Regul", "Heavy"],
    "exercise": ["None", "Some", "Freq"],
    "writing_hand": ["Left", "Right"],
    "sex": ["Female", "Male"],
}
g = "sex"
df = pd.read_parquet("tests/parity/fixtures/s1_survey.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,
})

Build one on your own data. Use Characteristics for the rows and Groups for the columns. Then find the switches for Test for differences between groups, Standardized mean differences (two groups) and Show missing counts.

03

Do the p-values stay?

Predict

Predict first

You're writing up a randomized trial. Should the Table 1 have a column of p-values?

Keep them, they check the randomizationTurn them off, and keep the standardized differencesKeep only the significant ones
Reveal

Turn them off. Differences at baseline in a randomized trial arise by chance, so those tests ask a question you already know the answer to. CONSORT advises against them. In an observational study they're descriptive at best. The standardized difference tells you the size of an imbalance in either kind of study.

04

Rows a reader can use

Read

Whichever columns you keep, make each row self-explanatory:

  • Group sizes in the header, so every percentage has a visible denominator.
  • Say what each number is: mean (SD), median [IQR], n (%).
  • Units on every measure.
  • Missing counts, so nobody has to work out why the numbers don't add up.
  • Order by meaning: demographics, then baseline measures, rather than the order of your file's columns.
05

Mean or median?

Explore

On your table, look at which summary each numeric row uses. Numeric summary set to Automatic picks mean (SD) unless a variable is skewed or has far-out values, and then uses median [IQR].

Switch it to Mean (SD) for one run, and compare a skewed row. Would a reader get the right picture of a typical value from it?

Mixed rows are fine, as long as each row says what it shows. A table note can say how the choice was made.

06

The words that go with it

Read

Don't read the table aloud. Say who, how many, and the one thing a reader should notice.

The sample comprised 236 respondents. The largest difference between the groups was in height (standardized difference 1.79).

Then say what you did about it. A height difference between sexes is no surprise, and it only matters if height could affect your outcome. If it could, say how you adjusted for it.

07

Into a report

In the app

Save the analysis, then press Add to report on its card. An APA results report numbers its tables and figures for you, in order.

Add a Text item above it with your two sentences, and read them together in the preview. Does the text tell the reader where to look?

08

Check your understanding

Checkpoint

Check yourself

A row reads "Smoker: 42 (35%)". What else does a reader need in order to trust that percentage?

Show the answer

Answer: a

Group sizes in the header and a missing count give the reader the denominator. Show the count even when it's zero for most rows.

Check yourself

An observational study's Table 1 has age with a standardized difference of 0.6. What should the text do?

Show the answer

Answer: b

A large imbalance on something related to the outcome is a threat to the comparison. Readers shouldn't have to find that for themselves.

Check yourself

Your dataset has 40 columns. How many belong in Table 1?

Show the answer

Answer: b

Choosing rows by significance hides exactly what a reader should see. Put the rest in an appendix or a data quality report.

09

Yours

Reflect

Look at a Table 1 you've written or read lately. Which row would you cut? Which missing row would you add, knowing who reads it?

10

Recap

Recap
  • A Table 1 tells readers who was studied and what else could explain the result.
  • Turn p-values off for a randomized trial, and report the size of any imbalance.
  • Label every number, show the missing counts, and point out what matters in words.

Concepts in this lesson