Skip to content

Screening many columns

A screen measures every column against one outcome. Read its q-values, catch leaks before they become findings, check within groups, mind repeated rows, and write "associated with".

Applied ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Read q-values, not raw p-values, when many columns were screened
  • Spot a column that leaks the outcome before it becomes a finding
  • Check a screened relationship within the groups of another column
  • Explain why repeated rows make a screen too sure of itself
  • Report a screen with "associated with", not "drives"

Read first

01

Forty columns of noise

Predict

Predict first

You screen 40 columns against one outcome. None of them has anything to do with it. How many do you expect below 0.05 on raw p-values?

Make your guess between 0 and 40 columns, then reveal.

Reveal

The answer: 2

About two, since 40 × 0.05 = 2. Each test has a 5% chance of a false alarm, and a screen runs one test per column. Screen 200 columns and expect about ten. A list sorted by p-value always has something at the top.

02

Read q, not p

Read

An association screenAssociation screenEach candidate column measured against one outcome on its own, with q-values across the columns and a held-out score to rank them. sorts leads from noise across every column at once. Its q-valueFalse discovery rateThe expected share of false positives among the results you call significant. is each column's p-value adjusted for all the columns tested, with Benjamini–Hochberg. Among the columns below q = 0.05, you expect at most 5 in 100 to be false leads.

In Guided, the Relationships step shows q-tiers only: q < .01, q < .05, one looser tier, or Not significant. It never shows a raw p-value. It's a quick look on a sample, and it records nothing in the ledger.

Record as an analysis runs the same screen on all rows as an Analyze method. That run joins the ledger like any other test.

Python
import numpy as np
from scipy import stats
from statsmodels.stats.multitest import multipletests

rng = np.random.default_rng(1)
y = rng.normal(size=200)
X = rng.normal(size=(200, 40))  # 40 columns of pure noise
p = [stats.spearmanr(X[:, j], y).pvalue for j in range(40)]
q = multipletests(p, method="fdr_bh")[1]
print("raw p < 0.05:", sum(v < 0.05 for v in p))
print("q < 0.05:", sum(v < 0.05 for v in q))
R
set.seed(1)
y <- rnorm(200)
X <- matrix(rnorm(200 * 40), ncol = 40)  # 40 columns of pure noise
p <- apply(X, 2, function(x) cor.test(x, y, method = "spearman")$p.value)
q <- p.adjust(p, method = "BH")
cat("raw p < 0.05:", sum(p < 0.05), "\n")
cat("q < 0.05:", sum(q < 0.05), "\n")
03

Too good to be true

Read

In the birth-weight data, low marks babies born under 2,500 grams. Here is a screen of every other column against low.

Association screenRecorded · Python and R agreeRecorded 2026-11-26 · 149 values compared
R

bwt: AUC = 0.00, adjusted p < .001 (BH, m = 9)

Features tested
9
q < 0.05
5
Smallest q
< .001

Plots

How strongly each feature relates to lowWhich categories lead on a total, mean or median?
View data
FeatureStrength (0–1)
bwt1
mother weight (lb)0.2262
ptl0.2063
ui0.1529
smoke0.1444
ht0.1341
race0.1262
age0.1051
ftv0.0978

Assumptions

  • Independent rows — p- and q-values assume each row is a separate unit; repeated rows per subject or cluster make them too small.
  • Rows per feature — Sparse tables (expected counts below 5): ht

Features against low

FeatureKindLevelsMeasureValueStrength (0–1)DirectionTestStatisticdfdf₂pq (Benjamini–Hochberg (FDR))nMissingHeld-out scoreFlags
agenumeric—auc0.44750.1051negativemann_whitney3,432——.247.2471890.0%−0.0366
mother weight (lb)numeric—auc0.38690.2262negativemann_whitney2967.50——.013.0381890.0%−0.0081
racecategorical3cramers_v_bc0.12620.1262—chisq5.0052—.082.1051890.0%−0.0018
smokecategorical2cramers_v_bc0.14440.1444positivechisq4.9241—.026.0481890.0%0.0119
ptlnumeric—auc0.60310.2063positivemann_whitney4,626——< .001.0021890.0%0.0443
htcategorical2cramers_v_bc0.13410.1341positivechisq4.3881—.036.0541890.0%0.0054sparse
uicategorical2cramers_v_bc0.15290.1529positivechisq5.4011—.020.0451890.0%0.0097
ftvnumeric—auc0.45110.0978negativemann_whitney3,460——.238.2471890.0%−0.0019
bwtnumeric—auc01negativemann_whitney0——< .001< .0011890.0%0.9568possible_leakage
  • Each feature uses the rows where it and low are present; q adjusts over the 9 features with a p-value (Benjamini–Hochberg (FDR)).
  • Strength puts every measure on 0–1: |ρ| or |r|, η² or ε², |2·AUC − 1|, Cramér's V. The positive level of low is true.
  • Held-out score: 5 folds by row position; numeric features in 10 quantile bins; log-loss reduction against the training class shares.
  • A screen looks at one feature at a time: a feature can matter alone and not once others are included, and the other way round. Associations are not causes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Association screen (one outcome, many features)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method association.screen 1.0.0 · spec 8615052531435f59
# Dataset: birthwt (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 feature uses the rows where it and the outcome are present)
outcome <- "low"
features <- setdiff(unique(c("age", "mother weight (lb)", "race", "smoke", "ptl", "ht", "ui", "ftv", "bwt")), outcome)
kinds <- c(
  "low" = "boolean",
  "age" = "numeric",
  "mother weight (lb)" = "numeric",
  "race" = "categorical",
  "smoke" = "boolean",
  "ptl" = "numeric",
  "ht" = "boolean",
  "ui" = "boolean",
  "ftv" = "numeric",
  "bwt" = "numeric"
)
level_order <- list(
  "low" = c("false", "true"),
  "race" = c("white", "black", "other"),
  "smoke" = c("false", "true"),
  "ht" = c("false", "true"),
  "ui" = c("false", "true")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/birthwt.parquet", col_select = c(outcome, features)))
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, c(outcome, features))  # infinite values stop the run (registry/errors.yaml)
warnings <- list()
if (outcome %in% c("age", "mother weight (lb)", "race", "smoke", "ptl", "ht", "ui", "ftv", "bwt")) warnings <- c(warnings, sprintf("%s is the outcome, so it was not screened as a feature.", outcome))
if (n_input == 0) cs_error("CS_E_NO_ROWS")
present <- !is.na(df[[outcome]])
if (!any(present)) cs_error("CS_E_ALL_MISSING", column = outcome)
n_rows <- sum(present)  # rows with the outcome present
cs_check_rows(n_rows, 3, "The association screen")
if (n_rows < n_input) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - n_rows, total = n_input))
if (kinds[[outcome]] == "numeric") {
  y_num <- as.numeric(df[[outcome]])
  values_y <- sort(unique(y_num[present]))
  if (length(values_y) < 2) cs_error("CS_E_CONSTANT", column = outcome)
  if (length(values_y) == 2) {  # two values: a yes/no outcome, the larger value positive
    outcome_kind <- "binary"
    n_classes <- 2L
    class_levels <- format(values_y)
    y_all <- match(y_num, values_y)
  } else {
    outcome_kind <- "numeric"
    n_classes <- 0L
    class_levels <- character(0)
    y_all <- y_num
  }
} else {
  # Class codes 1..K over the levels with rows, in stored order; the positive level is the second.
  codes <- as.integer(df[[outcome]])
  used <- sort(unique(codes[present]))
  n_classes <- length(used)
  if (n_classes < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = outcome, min = 2, k = n_classes)
  class_levels <- levels(df[[outcome]])[used]
  y_all <- match(codes, used)
  outcome_kind <- if (n_classes == 2) "binary" else "categorical"
}

# %% Options (written out so the engines agree)
policy <- "auto"  # auto (the quick look's measures) | rank | linear
adjust <- "BH"  # BH | BY | holm, over the features with a p-value
min_level_count <- as.integer(5)
collapse_rare <- TRUE  # rarer levels of a categorical feature share one level
k <- as.integer(5)  # 0 or 1 = no held-out score
alpha <- 0.05
folds <- if (k >= 2) (seq_len(n_input) - 1L) %% k else NULL  # fold of a row = 0-based row position mod k

# %% Screen (one row per feature)
adjust_labels <- c(BH = "Benjamini–Hochberg (FDR)", BY = "Benjamini–Yekutieli (FDR)", holm = "Holm")
rows <- lapply(features, function(f) {
  ok <- present & !is.na(df[[f]])
  if (kinds[[f]] == "numeric") {
    fk <- "numeric"
    x <- as.numeric(df[[f]])[ok]
    n_levels <- 0L
  } else {
    fk <- "categorical"
    x <- as.integer(df[[f]])[ok]
    n_levels <- nlevels(df[[f]])
  }
  res <- cs_screen_pair(y_all[ok], x, outcome_kind, fk, policy, n_classes, n_levels,
                        if (is.null(folds)) NULL else folds[ok], k, min_level_count, collapse_rare,
                        sum(is.na(df[[f]])) / n_input)  # share of all rows where f is missing
  c(list(feature = f, kind = fk), res)
})
q <- cs_p_adjust(vapply(rows, function(r) r$p, 0), adjust)  # the family: every feature with a p-value
for (i in seq_along(rows)) rows[[i]]$q <- q[i]

# %% Result
p_all <- vapply(rows, function(r) r$p, 0)
cv_all <- vapply(rows, function(r) r$cv_score, 0)
tested <- which(!is.na(p_all))
m <- length(tested)
top <- if (m > 0) rows[[which.min(p_all)]] else NULL  # smallest p; the first on ties
best <- if (any(!is.na(cv_all))) rows[[which.max(cv_all)]] else NULL  # largest held-out score; the first on ties
q_tested <- q[tested]
n_sig <- sum(q_tested < alpha)
symbol <- c(spearman = "ρ", pearson = "r", r_pb = "r", auc = "AUC", eta2 = "η²", epsilon2 = "ε²", cramers_v = "V", cramers_v_bc = "V (bias-corrected)")
values <- list(
  m = m, n = n_rows, n_features = length(features), outcome_kind = outcome_kind,
  p_min_adj = if (m > 0) min(q_tested) else NA_real_,
  n_q05 = sum(q_tested < 0.05), n_significant = n_sig,
  top_feature = if (!is.null(top)) top$feature else NA_character_, top_measure = if (!is.null(top)) top$measure else NA_character_,
  top_symbol = if (!is.null(top)) symbol[[top$measure]] else NA_character_,
  top_value = if (!is.null(top)) top$value else NA_real_, top_q = if (!is.null(top)) top$q else NA_real_,
  best_cv_feature = if (!is.null(best)) best$feature else NA_character_, best_cv_score = if (!is.null(best)) best$cv_score else NA_real_
)
keys <- c("measure", "value", "strength", "direction", "test", "statistic", "df", "df2", "p", "q", "n", "missing_share", "cv_score", "levels")
for (r in rows) {
  for (key in keys) values[[sprintf("%s[%s]", key, r$feature)]] <- r[[key]]
  values[[sprintf("flags[%s]", r$feature)]] <- paste(r$flags, collapse = ", ")
}

num <- function(v) if (is.na(v)) "—" else cs_fmt_num(v)
if (!is.null(top)) {
  summary <- sprintf("%d of %d features could be tested against %s (n = %d). %d %s q < %s after %s adjustment; the smallest q is for %s (%s = %s, adjusted %s).",
                     m, length(features), outcome, n_rows, n_sig, if (n_sig == 1) "has" else "have", format(alpha), adjust_labels[[adjust]],
                     top$feature, symbol[[top$measure]], num(top$value), cs_fmt_p(top$q))
  apa <- sprintf("%s: %s = %s, adjusted %s (%s, m = %d)", top$feature, symbol[[top$measure]], num(top$value), cs_fmt_p(top$q), adjust, m)
} else {
  summary <- sprintf("None of the %d features could be tested against %s; the Flags column says why.", length(features), outcome)
  apa <- summary
  warnings <- c(warnings, "No feature could be tested; the Flags column says why.")
}
if (!is.null(best)) summary <- paste0(summary, sprintf(" On held-out rows, %s predicts %s best on its own (score %s).", best$feature, outcome, cs_fmt_num(best$cv_score)))
small <- vapply(Filter(function(r) !is.na(r$p) && r$n < 30, rows), function(r) r$feature, "")
sparse <- vapply(Filter(function(r) "sparse" %in% r$flags, rows), function(r) r$feature, "")
size_detail <- paste(c(if (length(small)) sprintf("Fewer than 30 complete rows: %s", paste(small, collapse = ", ")),
                       if (length(sparse)) sprintf("Sparse tables (expected counts below 5): %s", paste(sparse, collapse = ", "))), collapse = "; ")
assumptions <- list(
  list(key = "independence", label = "Independent rows", status = "info",
       detail = "p- and q-values assume each row is a separate unit; repeated rows per subject or cluster make them too small."),
  list(key = "sample_size", label = "Rows per feature", status = if (length(small) || length(sparse)) "warn" else "pass",
       detail = if (nzchar(size_detail)) size_detail else "Every tested feature has at least 30 complete rows and no sparse table.")
)
strength_all <- vapply(rows, function(r) r$strength, 0)
shown <- which(!is.na(strength_all))
shown <- shown[order(-strength_all[shown], method = "radix")]
charts <- if (length(shown)) list(cs_chart("strength", "bar-ranked", sprintf("How strongly each feature relates to %s", outcome), list(
  category = cs_col("Feature", features[shown], "categorical", levels = features[shown]),
  value = cs_col("Strength (0–1)", strength_all[shown], "numeric")
), controls = list(agg = "sum", top = max(3, min(30, length(shown)))))) else list()
cv_note <- if (k >= 2) paste0(sprintf("Held-out score: %d folds by row position; numeric features in 10 quantile bins; ", k),
                              if (outcome_kind == "numeric") "1 − MSE / MSE of the training mean." else "log-loss reduction against the training class shares.") else "Held-out scores are off."
table_rows <- lapply(rows, function(r) c(r[c("feature", "kind", keys)], list(flags = paste(r$flags, collapse = ", "))))
cs_publish(list(
  method = "association.screen",
  methodVersion = "1.0.0",
  title = "Association screen",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_rows,
  summary = summary,
  apa = apa,
  statistics = list(list(key = "m", label = "Features tested", value = m, format = "integer"),
                    list(key = "n_significant", label = sprintf("q < %s", format(alpha)), value = n_sig, format = "integer"),
                    list(key = "p_min_adj", label = "Smallest q", value = values$p_min_adj, format = "p")),
  tables = list(list(key = "features", title = sprintf("Features against %s", outcome), columns = list(
    list(key = "feature", label = "Feature", type = "string"), list(key = "kind", label = "Kind", type = "string"),
    list(key = "levels", label = "Levels", type = "integer"), list(key = "measure", label = "Measure", type = "string"),
    list(key = "value", label = "Value", type = "number"), list(key = "strength", label = "Strength (0–1)", type = "number"),
    list(key = "direction", label = "Direction", type = "string"), list(key = "test", label = "Test", type = "string"),
    list(key = "statistic", label = "Statistic", type = "number"), list(key = "df", label = "df", type = "number"),
    list(key = "df2", label = "df₂", type = "number"), list(key = "p", label = "p", type = "pvalue"),
    list(key = "q", label = sprintf("q (%s)", adjust_labels[[adjust]]), type = "pvalue"), list(key = "n", label = "n", type = "integer"),
    list(key = "missing_share", label = "Missing", type = "percent"), list(key = "cv_score", label = "Held-out score", type = "number"),
    list(key = "flags", label = "Flags", type = "string")), rows = table_rows)),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Each feature uses the rows where it and %s are present; q adjusts over the %d features with a p-value (%s).", outcome, m, adjust_labels[[adjust]]),
               paste0("Strength puts every measure on 0–1: |ρ| or |r|, η² or ε², |2·AUC − 1|, Cramér's V.",
                      if (outcome_kind == "binary") sprintf(" The positive level of %s is %s.", outcome, class_levels[2]) else ""),
               cv_note,
               "A screen looks at one feature at a time: a feature can matter alone and not once others are included, and the other way round. Associations are not causes."),
  charts = charts,
  values = values
))
Python

bwt: AUC = 0.00, adjusted p < .001 (BH, m = 9)

Features tested
9
q < 0.05
5
Smallest q
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Independent rows — p- and q-values assume each row is a separate unit; repeated rows per subject or cluster make them too small.
  • Rows per feature — Sparse tables (expected counts below 5): ht

Features against low

FeatureKindLevelsMeasureValueStrength (0–1)DirectionTestStatisticdfdf₂pq (Benjamini–Hochberg (FDR))nMissingHeld-out scoreFlags
agenumeric—auc0.44750.1051negativemann_whitney3,432——.247.2471890.0%−0.0366
mother weight (lb)numeric—auc0.38690.2262negativemann_whitney2967.50——.013.0381890.0%−0.0081
racecategorical3cramers_v_bc0.12620.1262—chisq5.0052—.082.1051890.0%−0.0018
smokecategorical2cramers_v_bc0.14440.1444positivechisq4.9241—.026.0481890.0%0.0119
ptlnumeric—auc0.60310.2063positivemann_whitney4,626——< .001.0021890.0%0.0443
htcategorical2cramers_v_bc0.13410.1341positivechisq4.3881—.036.0541890.0%0.0054sparse
uicategorical2cramers_v_bc0.15290.1529positivechisq5.4011—.020.0451890.0%0.0097
ftvnumeric—auc0.45110.0978negativemann_whitney3,460——.238.2471890.0%−0.0019
bwtnumeric—auc01negativemann_whitney0——< .001< .0011890.0%0.9568possible_leakage
  • Each feature uses the rows where it and low are present; q adjusts over the 9 features with a p-value (Benjamini–Hochberg (FDR)).
  • Strength puts every measure on 0–1: |ρ| or |r|, η² or ε², |2·AUC − 1|, Cramér's V. The positive level of low is true.
  • Held-out score: 5 folds by row position; numeric features in 10 quantile bins; log-loss reduction against the training class shares.
  • A screen looks at one feature at a time: a feature can matter alone and not once others are included, and the other way round. Associations are not causes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Association screen (one outcome, many features)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method association.screen 1.0.0 · spec 8615052531435f59
# Dataset: birthwt (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

import codesplash as cs
from codesplash.stats import screen as css
from codesplash.stats.padjust import LABELS as ADJUST_LABELS, p_adjust

# %% Data (each feature uses the rows where it and the outcome are present)
outcome = "low"
features = [f for f in dict.fromkeys(["age", "mother weight (lb)", "race", "smoke", "ptl", "ht", "ui", "ftv", "bwt"]) if f != outcome]
kinds = {"age":"numeric","bwt":"numeric","ftv":"numeric","ht":"boolean","low":"boolean","mother weight (lb)":"numeric","ptl":"numeric","race":"categorical","smoke":"boolean","ui":"boolean"}
level_order = {
    "low": ["false", "true"],
    "race": ["white", "black", "other"],
    "smoke": ["false", "true"],
    "ht": ["false", "true"],
    "ui": ["false", "true"],
}
df = pd.read_parquet("tests/parity/fixtures/birthwt.parquet", columns=[outcome] + features)
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, [outcome] + features)  # infinite values stop the run (registry/errors.yaml)
warnings = []
if outcome in ["age", "mother weight (lb)", "race", "smoke", "ptl", "ht", "ui", "ftv", "bwt"]:
    warnings.append(f"{outcome} is the outcome, so it was not screened as a feature.")
if n_input == 0:
    cs.cs_error("CS_E_NO_ROWS")
present = df[outcome].notna().to_numpy()
if not present.any():
    cs.cs_error("CS_E_ALL_MISSING", column=outcome)
n_rows = int(present.sum())  # rows with the outcome present
cs.check_rows(n_rows, 3, "The association screen")
if n_rows < n_input:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - n_rows, total=n_input))
if kinds[outcome] == "numeric":
    y_num = df[outcome].to_numpy(dtype=float, na_value=np.nan)
    values_y = np.unique(y_num[present])
    if values_y.size < 2:
        cs.cs_error("CS_E_CONSTANT", column=outcome)
    if values_y.size == 2:  # two values: a yes/no outcome, the larger value positive
        outcome_kind, n_classes, class_levels = "binary", 2, [f"{v:g}" for v in values_y]
        y_all = np.full(n_input, -1)
        y_all[present] = (y_num[present] == values_y[1]).astype(int)
    else:
        outcome_kind, n_classes, class_levels = "numeric", 0, []
        y_all = y_num
else:
    # Class codes 0..K−1 over the levels with rows, in stored order; the positive level is the second.
    codes = df[outcome].cat.codes.to_numpy()
    used = np.unique(codes[present])
    n_classes = int(used.size)
    if n_classes < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=outcome, min=2, k=n_classes)
    class_levels = [str(df[outcome].cat.categories[i]) for i in used]
    remap = np.full(len(df[outcome].cat.categories), -1)
    remap[used] = np.arange(n_classes)
    y_all = np.full(n_input, -1)
    y_all[present] = remap[codes[present]]
    outcome_kind = "binary" if n_classes == 2 else "categorical"

# %% Options (written out so the engines agree)
policy = "auto"  # auto (the quick look's measures) | rank | linear
adjust = "BH"  # BH | BY | holm, over the features with a p-value
min_level_count = int(5)
collapse_rare = True  # rarer levels of a categorical feature share one level
k = int(5)  # 0 or 1 = no held-out score
alpha = 0.05
folds = np.arange(n_input) % k if k >= 2 else None  # fold of a row = 0-based row position mod k

# %% Screen (one row per feature)
rows = []
for f in features:
    ok = present & df[f].notna().to_numpy()
    if kinds[f] == "numeric":
        fk, x, n_levels = "numeric", df[f].to_numpy(dtype=float, na_value=np.nan)[ok], 0
    else:
        fk, x, n_levels = "categorical", df[f].cat.codes.to_numpy()[ok], len(df[f].cat.categories)
    res = css.pair(y_all[ok], x, outcome_kind=outcome_kind, feature_kind=fk, policy=policy, n_classes=n_classes,
                   n_levels=n_levels, folds=None if folds is None else folds[ok], k=k,
                   min_level_count=min_level_count, collapse_rare=collapse_rare,
                   missing_share=int(df[f].isna().sum()) / n_input)  # share of all rows where f is missing
    rows.append({"feature": f, "kind": fk, **res})
q = p_adjust([np.nan if r["p"] is None else r["p"] for r in rows], adjust)  # the family: every feature with a p-value
for r, qv in zip(rows, q):
    r["q"] = None if np.isnan(qv) else float(qv)

# %% Result
tested = [r for r in rows if r["p"] is not None]
m = len(tested)
top = min(tested, key=lambda r: r["p"]) if tested else None  # smallest p; the first on ties
scored = [r for r in rows if r["cv_score"] is not None]
best = max(scored, key=lambda r: r["cv_score"]) if scored else None  # largest held-out score; the first on ties
n_sig = sum(r["q"] < alpha for r in tested)
SYMBOL = {"spearman": "ρ", "pearson": "r", "r_pb": "r", "auc": "AUC", "eta2": "η²", "epsilon2": "ε²", "cramers_v": "V", "cramers_v_bc": "V (bias-corrected)"}
values = {
    "m": m, "n": n_rows, "n_features": len(features), "outcome_kind": outcome_kind,
    "p_min_adj": min(r["q"] for r in tested) if tested else None,
    "n_q05": sum(r["q"] < 0.05 for r in tested), "n_significant": n_sig,
    "top_feature": top["feature"] if top else None, "top_measure": top["measure"] if top else None,
    "top_symbol": SYMBOL[top["measure"]] if top else None,
    "top_value": top["value"] if top else None, "top_q": top["q"] if top else None,
    "best_cv_feature": best["feature"] if best else None, "best_cv_score": best["cv_score"] if best else None,
}
KEYS = ("measure", "value", "strength", "direction", "test", "statistic", "df", "df2", "p", "q", "n", "missing_share", "cv_score", "levels")
for r in rows:
    for key in KEYS:
        values[f"{key}[{r['feature']}]"] = r[key]
    values[f"flags[{r['feature']}]"] = ", ".join(r["flags"])

def num(v):
    return "—" if v is None else cs.fmt_num(v)


if top:
    summary = (
        f"{m} of {len(features)} features could be tested against {outcome} (n = {n_rows}). {n_sig} "
        f"{'has' if n_sig == 1 else 'have'} q < {alpha:g} after {ADJUST_LABELS[adjust]} adjustment; the smallest q is for "
        f"{top['feature']} ({SYMBOL[top['measure']]} = {num(top['value'])}, adjusted {cs.fmt_p(top['q'])})."
    )
    apa = f"{top['feature']}: {SYMBOL[top['measure']]} = {num(top['value'])}, adjusted {cs.fmt_p(top['q'])} ({adjust}, m = {m})"
else:
    summary = f"None of the {len(features)} features could be tested against {outcome}; the Flags column says why."
    apa = summary
    warnings.append("No feature could be tested; the Flags column says why.")
if best:
    summary += f" On held-out rows, {best['feature']} predicts {outcome} best on its own (score {cs.fmt_num(best['cv_score'])})."
small = [r["feature"] for r in tested if r["n"] < 30]
sparse = [r["feature"] for r in rows if "sparse" in r["flags"]]
assumptions = [
    {"key": "independence", "label": "Independent rows", "status": "info",
     "detail": "p- and q-values assume each row is a separate unit; repeated rows per subject or cluster make them too small."},
    {"key": "sample_size", "label": "Rows per feature", "status": "warn" if small or sparse else "pass",
     "detail": "; ".join(([f"Fewer than 30 complete rows: {', '.join(small)}"] if small else [])
                         + ([f"Sparse tables (expected counts below 5): {', '.join(sparse)}"] if sparse else []))
     or "Every tested feature has at least 30 complete rows and no sparse table."},
]
shown = sorted((r for r in rows if r["strength"] is not None), key=lambda r: -r["strength"])
charts = [cs.chart("strength", "bar-ranked", f"How strongly each feature relates to {outcome}", {
    "category": cs.col("Feature", [r["feature"] for r in shown], "categorical", levels=[r["feature"] for r in shown]),
    "value": cs.col("Strength (0–1)", [r["strength"] for r in shown], "numeric"),
}, controls={"agg": "sum", "top": max(3, min(30, len(shown)))})] if shown else []
cv_note = (f"Held-out score: {k} folds by row position; numeric features in 10 quantile bins; "
           + ("1 − MSE / MSE of the training mean." if outcome_kind == "numeric" else "log-loss reduction against the training class shares.")
           if k >= 2 else "Held-out scores are off.")
cs.publish({
    "method": "association.screen",
    "methodVersion": "1.0.0",
    "title": "Association screen",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n_rows,
    "summary": summary,
    "apa": apa,
    "statistics": [{"key": "m", "label": "Features tested", "value": m, "format": "integer"},
                   {"key": "n_significant", "label": f"q < {alpha:g}", "value": n_sig, "format": "integer"},
                   {"key": "p_min_adj", "label": "Smallest q", "value": values["p_min_adj"], "format": "p"}],
    "tables": [{"key": "features", "title": f"Features against {outcome}", "columns": [
        {"key": "feature", "label": "Feature", "type": "string"}, {"key": "kind", "label": "Kind", "type": "string"},
        {"key": "levels", "label": "Levels", "type": "integer"}, {"key": "measure", "label": "Measure", "type": "string"},
        {"key": "value", "label": "Value", "type": "number"}, {"key": "strength", "label": "Strength (0–1)", "type": "number"},
        {"key": "direction", "label": "Direction", "type": "string"}, {"key": "test", "label": "Test", "type": "string"},
        {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "df", "label": "df", "type": "number"},
        {"key": "df2", "label": "df₂", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        {"key": "q", "label": f"q ({ADJUST_LABELS[adjust]})", "type": "pvalue"}, {"key": "n", "label": "n", "type": "integer"},
        {"key": "missing_share", "label": "Missing", "type": "percent"}, {"key": "cv_score", "label": "Held-out score", "type": "number"},
        {"key": "flags", "label": "Flags", "type": "string"}],
        "rows": [{**{c: r[c] for c in ("feature", "kind") + KEYS}, "flags": ", ".join(r["flags"])} for r in rows]}],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Each feature uses the rows where it and {outcome} are present; q adjusts over the {m} features with a p-value ({ADJUST_LABELS[adjust]}).",
              "Strength puts every measure on 0–1: |ρ| or |r|, η² or ε², |2·AUC − 1|, Cramér's V." + (f" The positive level of {outcome} is {class_levels[1]}." if outcome_kind == "binary" else ""),
              cv_note,
              "A screen looks at one feature at a time: a feature can matter alone and not once others are included, and the other way round. Associations are not causes."],
    "charts": charts,
    "values": values,
})

The feature with the smallest q is bwt, the birth weight itself. Its strength is 1.00 on a 0–1 scale, and its flags read possible_leakage. That isn't a discovery. low was made from bwt, so bwt is the outcome written another way.

A column this strong raises a question rather than answering one: where did it come from, and when was it recorded? A column made from the outcome, or recorded after it, is leakageData leakageInformation from the validation data or the future seeps into training, so scores look better than reality..

Method guide · association.screenAssociation screen (one outcome, many features)Which of many columns are associated with an outcome?
04

Leaks are rarely this obvious

In the app

Real leaks hide better: a refund issued after a customer left, a code entered after a diagnosis, a column whose name contains the outcome's. The screen flags a column as a possible leak when it predicts the outcome almost perfectly on its own.

In Guided, Columns & roles lists these under Leave out with the flag Possible leakage. Choosing the outcome opens a check that lists the columns that may leak it. Leaks are never ticked for you, because some strong columns are real. Suggested without leakage leaves them all out at once.

05

The same pair, the other way round

Explore

A screen measures each column against the outcome on its own. Within the groups of a third column, a pair can point the other way. That's Simpson's paradoxSimpson's paradoxA trend seen in the pooled data disappears or reverses inside the groups, because group size is tied to the outcome..

EExplorable · Simpson's paradox: Berkeley admissions

Can a comparison reverse when you split the data into groups?

Overall, men were admitted more often. Within departments, who is usually admitted more often?

How sure?

View

45%Men30%Women

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

The quick look checks its strongest columns within each Group by column. Without one, it uses the categorical columns that have a few large levels. A pair that flips gets a Simpson chip. Open it and use Control for… to see each group. Insights calls the same pattern Link reverses within groups, and Breakdown's badge says Reverses within.

06

Rows that repeat

Predict

Predict first

A join copies each patient's outcome onto all four of their visits. You screen the visit-level table. What happens?

Nothing: more rows give a better estimateThe tests become too sure of themselvesThe relationships get weaker
Reveal

The answer: The tests become too sure of themselves

The tests become too sure of themselves. Four copies of one outcome aren't four pieces of evidence, yet each test counts them as if they were. This is pseudoreplicationPseudoreplicationCounting several rows from one unit, such as one patient's visits, as separate pieces of evidence. p-values come out too small.: p-values and q-values come out far too small.

07

What the app does about it

In the app

When a Subject / ID column repeats, the facts strip on Columns & roles says so and asks you to confirm: Yes, rows repeat or No, each row is a different unit. If a Combine join copied the outcome, it offers Summarize per patient first or Keep rows as repeated measures, with your unit's name in place of "patient".

The quick look hides its q-tiers while rows repeat per subject. The strengths still show, because they describe the rows. The tests would claim more than the data hold.

08

Associated with

Reflect

A strong screen score says that a column and the outcome move together in these rows. It doesn't say which causes which, or whether a third column causes both.

Controlling for others reads all the features in one model, and a column that only traveled with a stronger one can drop out. Test this tests one pair properly, on a branch of the plan. Neither makes the screen causal. Take the top three columns from a screen you've run, and write one sentence for each that a skeptic would accept.

09

Check your understanding

Checkpoint

Check yourself

A screen of 60 columns reports one with raw p = 0.03 and q = 0.41. How should you describe it?

Show the answer

Answer: b

The q-value is the one that allows for the search. At 0.41, a column like this is as likely to be noise as a lead. If it matters to you, test it on new data.

Check yourself

In a churn table, cancellation_reason predicts churned almost perfectly on rows it wasn't fitted on. What's the best next step?

Show the answer

Answer: b

A held-out score can't detect leakage: the leak is in every fold. Only the timing of the column can tell you, and here the reason exists only for customers who already left.

Check yourself

A screen shows that customers who used support more were less likely to renew. Within each plan, they were more likely to renew. Which statement fits?

Show the answer

Answer: c

That's the Simpson pattern. Which view answers your question depends on how plan, support and renewal cause each other, and the screen can't tell you that.

Check yourself

Which sentence reports a screen honestly?

Show the answer

Answer: c

It names the search, the denominator and the association, and it claims nothing about cause.

10

Recap

Recap
  • A screen runs one test per column, so read q-values, not raw p-values.
  • A column that predicts the outcome almost perfectly is a question about timing.
  • Check strong pairs within groups, and don't let repeated rows pass as independent evidence.
  • Write "associated with", and test a lead on a branch or on new data.

Concepts in this lesson