CAssociation · association.screen
Association screen (one outcome, many features)
Which of many columns are associated with an outcome?
Screens 1–200 features against one outcome, each on its own: a measure fitted to the pair of column types (Spearman ρ, η², AUC or Cramér's V) with its test, q-values adjusted across the features (Benjamini–Hochberg by default), each feature's held-out predictive score from cross-validation, and flags for missing, constant, rare-level, sparse and possible-leakage columns.
A real result
Example “Lab a numeric”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
y_recorded_later: ρ = 1.00, adjusted p < .001 (BH, m = 10)
- Features tested
- 10
- q < 0.05
- 4
- Smallest q
- < .001
Plots
View data
| Feature | Strength (0–1) |
|---|---|
| y_recorded_later | 1 |
| x1 | 0.8988 |
| x2 | 0.2479 |
| segment | 0.0815 |
| x3 | 0.0633 |
| x8 | 0.0537 |
| x7 | 0.0513 |
| x5 | 0.0416 |
| x4 | 0.0330 |
| x6 | 0.0042 |
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 — Every tested feature has at least 30 complete rows and no sparse table.
Features against y
| Feature | Kind | Levels | Measure | Value | Strength (0–1) | Direction | Test | Statistic | df | df₂ | p | q (Benjamini–Hochberg (FDR)) | n | Missing | Held-out score | Flags |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| x1 | numeric | — | spearman | 0.8988 | 0.8988 | positive | spearman | 39.548 | 372 | — | < .001 | < .001 | 374 | 6.5% | 0.7766 | |
| x2 | numeric | — | spearman | −0.2479 | 0.2479 | negative | spearman | −5.000 | 382 | — | < .001 | < .001 | 384 | 4.0% | 0.0399 | |
| x3 | numeric | — | spearman | 0.0633 | 0.0633 | positive | spearman | 1.227 | 374 | — | .221 | .441 | 376 | 6.0% | −0.0303 | |
| x4 | numeric | — | spearman | 0.0330 | 0.0330 | positive | spearman | 0.6293 | 363 | — | .530 | .588 | 365 | 8.8% | −0.0303 | |
| x5 | numeric | — | spearman | −0.0416 | 0.0416 | negative | spearman | −0.8066 | 375 | — | .420 | .526 | 377 | 5.8% | −0.0309 | |
| x6 | numeric | — | spearman | 0.0042 | 0.0042 | positive | spearman | 0.0825 | 379 | — | .934 | .934 | 381 | 4.8% | 0.0076 | |
| x7 | numeric | — | spearman | −0.0513 | 0.0513 | negative | spearman | −0.9890 | 371 | — | .323 | .462 | 373 | 6.8% | −0.0405 | |
| x8 | numeric | — | spearman | −0.0537 | 0.0537 | negative | spearman | −1.035 | 371 | — | .301 | .462 | 373 | 6.8% | −0.0475 | |
| segment | categorical | 7 | eta2 | 0.0815 | 0.0815 | — | kruskal | 30.495 | 6 | — | < .001 | < .001 | 400 | 0.0% | 0.0651 | collapsed |
| y_recorded_later | numeric | — | spearman | 1 | 1 | positive | spearman | — | 398 | — | < .001 | < .001 | 400 | 0.0% | 0.9647 | possible_leakage |
- Each feature uses the rows where it and y are present; q adjusts over the 10 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.
- Held-out score: 5 folds by row position; numeric features in 10 quantile bins; 1 − MSE / MSE of the training mean.
- 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.
y_recorded_later: ρ = 1.00, adjusted p < .001 (BH, m = 10)
- Features tested
- 10
- q < 0.05
- 4
- 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 — Every tested feature has at least 30 complete rows and no sparse table.
Features against y
| Feature | Kind | Levels | Measure | Value | Strength (0–1) | Direction | Test | Statistic | df | df₂ | p | q (Benjamini–Hochberg (FDR)) | n | Missing | Held-out score | Flags |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| x1 | numeric | — | spearman | 0.8988 | 0.8988 | positive | spearman | 39.548 | 372 | — | < .001 | < .001 | 374 | 6.5% | 0.7766 | |
| x2 | numeric | — | spearman | −0.2479 | 0.2479 | negative | spearman | −5.000 | 382 | — | < .001 | < .001 | 384 | 4.0% | 0.0399 | |
| x3 | numeric | — | spearman | 0.0633 | 0.0633 | positive | spearman | 1.227 | 374 | — | .221 | .441 | 376 | 6.0% | −0.0303 | |
| x4 | numeric | — | spearman | 0.0330 | 0.0330 | positive | spearman | 0.6293 | 363 | — | .530 | .588 | 365 | 8.8% | −0.0303 | |
| x5 | numeric | — | spearman | −0.0416 | 0.0416 | negative | spearman | −0.8066 | 375 | — | .420 | .526 | 377 | 5.8% | −0.0309 | |
| x6 | numeric | — | spearman | 0.0042 | 0.0042 | positive | spearman | 0.0825 | 379 | — | .934 | .934 | 381 | 4.8% | 0.0076 | |
| x7 | numeric | — | spearman | −0.0513 | 0.0513 | negative | spearman | −0.9890 | 371 | — | .323 | .462 | 373 | 6.8% | −0.0405 | |
| x8 | numeric | — | spearman | −0.0537 | 0.0537 | negative | spearman | −1.035 | 371 | — | .301 | .462 | 373 | 6.8% | −0.0475 | |
| segment | categorical | 7 | eta2 | 0.0815 | 0.0815 | — | kruskal | 30.495 | 6 | — | < .001 | < .001 | 400 | 0.0% | 0.0651 | collapsed |
| y_recorded_later | numeric | — | spearman | 1 | 1 | positive | spearman | — | 398 | — | < .001 | < .001 | 400 | 0.0% | 0.9647 | possible_leakage |
- Each feature uses the rows where it and y are present; q adjusts over the 10 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.
- Held-out score: 5 folds by row position; numeric features in 10 quantile bins; 1 − MSE / MSE of the training mean.
- 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.
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
- Lab a numericscreen_lab_a · features: x1, x2, x3, x4, x5, x6, x7, x8, segment, y_recorded_later · outcome: y
- Lab a flagsscreen_lab_a · features: x1, segment, constant_text, empty · outcome: y
- Lab a rank holmscreen_lab_a · features: x1, x2, x3, x4, x5, x6, x7, x8, segment · outcome: y
- Lab a linear by no cvscreen_lab_a · features: x1, x2, x3, x4, x5, x6, x7, x8, segment · outcome: y
- Lab a binaryscreen_lab_a · features: x1, x2, x3, x4, x5, x6, x7, x8, segment, x1_high, y_recorded_later · outcome: y_high
- Lab a binary linearscreen_lab_a · features: x1, x2, x1_high, x1_high01, segment · outcome: y_high
- Iris categoricaliris · features: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width · outcome: Species
- Iris rank ten foldsiris · features: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width · outcome: Species
In the guides
Where it sits in the decision guides
- Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
- Continuous–categorical: point-biserial, η · Statistics Guide · C — Test association
- Categorical–categorical: χ², Fisher, Cramér's V · Statistics Guide · C — Test association
- Monotonic / non-parametric / nominal relationships · Statistics Guide · C — Test association
- Model selection and structure (penalized, stepwise, SEM) · Statistics Guide · D — Predict an outcome
- Multiple comparisons · Statistics Guide · Additional considerations
- EDA (correlation, distributions) · DS & ML Decision Guide · Describe — summarize and visualize
- Correlation analysis (Pearson, Spearman) · DS & ML Decision Guide · Explain — why is it happening?
- Leakage checks: target copies, identifiers, future information · DS & ML Decision Guide · Prepare data for modelling
What you need
- Outcomenumeric / categorical / boolean · 1 column · 2–50 levels
- What you want to explain: a number, yes/no, or a few categories.
- Featuresnumeric / categorical / boolean · 1–200 columns
- The columns that might matter. Each one is screened on its own against the outcome.
Choices you make
statistics
- Measuresdefault auto
Which measure each feature gets. Automatic uses the quick look's measures; rank-based and linear use one family throughout.
- Automatic (as the quick look)(default) — Spearman ρ, η² with a Kruskal–Wallis test, AUC with a Mann–Whitney test, and bias-corrected Cramér's V with χ².
- Rank-based — Spearman ρ, rank ε² with Kruskal–Wallis, AUC with Mann–Whitney, and Cramér's V with χ²; robust to outliers and skew.
- Linear (means) — Pearson r, η² with the ANOVA F test, point-biserial r, and Cramér's V with χ²; best for roughly normal data.
hypothesis
- Multiplicity adjustment (q)default BH
How p-values are adjusted for screening many features. The family is every feature that could be tested.
- Benjamini–Hochberg (FDR)(default) — Controls the expected share of false positives among the findings; the usual choice for a screen.
- Benjamini–Yekutieli (FDR) — A stricter Benjamini–Hochberg that holds under any dependence between the features.
- Holm (family-wise) — Controls the chance of any false positive; strict when there are many features.
- Significance level for qdefault 0.05
Features with q below this count as significant.
options
- Merge rare levelsdefault on
Merge the rare levels of each categorical feature into one, so ID-like columns and tiny groups don't distort the tests.
- Smallest level keptdefault 5
Levels of a categorical feature with fewer rows than this are merged into one level.
validation
- Held-out score foldsdefault 5
Folds for each feature's held-out predictive score; rows are assigned by position. 0 turns the score off.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Independent rowsNot checked from data: state why it holds
p- and q-values assume each row is a separate unit; rows repeated per subject or cluster make them too small.
Rows per feature
Features with fewer than 30 complete rows, or tables with expected counts below 5, give unstable values.
What it reports
- Tests: Any feature associated with the outcome (smallest adjusted p)
- m
- How many features got a p-value. It is the family the q-values adjust over; flagged features without a test don't count.
- n
- n: rows with the outcome present. n[feature]: rows where both the outcome and that feature are present.
- n_features
- How many feature columns were screened, whether or not each could be tested.
- outcome_kind
- Numeric, binary (two values; the last level or larger value is positive) or categorical (3+ levels). It picks the measures.
- p_min_adj
- The smallest adjusted p across the features. Below α, at least one feature is associated with the outcome.
- n_q05
- How many features have an adjusted p-value below 0.05.
- n_significant
- How many features have q below the significance level you chose (0.05 unless changed).
- top_feature
- The feature with the most evidence of an association (smallest p; the first on ties). It isn't always the strongest one.
- top_measure
- The measure the top feature got: spearman, pearson, r_pb, auc, eta2, epsilon2, cramers_v or cramers_v_bc.
- top_symbol
- The symbol of the top feature's measure (ρ, r, AUC, η², ε² or V), as the summary prints it.
- top_value
- The top feature's measure: ρ, r, AUC, η², ε² or Cramér's V. Empty when the bias-corrected V is undefined.
- top_q
- The top feature's adjusted p-value (Benjamini–Hochberg unless you chose another adjustment).
- best_cv_feature
- The feature whose bins predict the outcome best on rows it didn't learn from (the largest held-out score).
- best_cv_score
- The best feature's held-out score; 0 means no better than predicting without any feature.
Per group, level or term: measure[<feature>], value[…], strength[…], direction[…], test[…], statistic[…], df[…], df2[…], p[…], q[…], n[…], missing_share[…], cv_score[…], levels[…], flags[…]
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
- Both engines run the codesplash twins (codesplash.stats.screen ↔ cs_screen_*): closed-form statistics, folds by row position and bin edges from exact integer index arithmetic, so the held-out scores agree to rounding too.
- p- and q-values come from each engine's t, normal, χ² and F tail functions (scipy and R's nmath), so they are compared at 1e-8, the P0 tolerance for p-values (docs/PLAN.md §11).
The exact script CodeSplash ran for example “Lab a numeric” · 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 33ef72be81d1a716
# Dataset: screen_lab_a (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 = "y"
features = [f for f in dict.fromkeys(["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "segment", "y_recorded_later"]) if f != outcome]
kinds = {"segment":"categorical","x1":"numeric","x2":"numeric","x3":"numeric","x4":"numeric","x5":"numeric","x6":"numeric","x7":"numeric","x8":"numeric","y":"numeric","y_recorded_later":"numeric"}
level_order = {
"segment": ["s0", "s1", "s2", "s3", "s4", "s5", "r98", "r99"],
}
df = pd.read_parquet("tests/parity/fixtures/screen_lab_a.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 ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "segment", "y_recorded_later"]:
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 exact script CodeSplash ran for example “Lab a numeric” · 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 33ef72be81d1a716
# Dataset: screen_lab_a (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 <- "y"
features <- setdiff(unique(c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "segment", "y_recorded_later")), outcome)
kinds <- c(
"y" = "numeric",
"x1" = "numeric",
"x2" = "numeric",
"x3" = "numeric",
"x4" = "numeric",
"x5" = "numeric",
"x6" = "numeric",
"x7" = "numeric",
"x8" = "numeric",
"segment" = "categorical",
"y_recorded_later" = "numeric"
)
level_order <- list(
"segment" = c("s0", "s1", "s2", "s3", "s4", "s5", "r98", "r99")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/screen_lab_a.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("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "segment", "y_recorded_later")) 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
))
Sources
- Spearman, C. (1904). The proof and measurement of association between two things. American Journal of Psychology, 15, 72–101.
- Kruskal, W. H., & Wallis, W. A. (1952). Use of ranks in one-criterion variance analysis. JASA, 47, 583–621.
- Mann, H. B., & Whitney, D. R. (1947). On a test of whether one of two random variables is stochastically larger than the other. Annals of Mathematical Statistics, 18, 50–60.
- Hanley, J. A., & McNeil, B. J. (1982). The meaning and use of the area under a receiver operating characteristic (ROC) curve. Radiology, 143, 29–36.
- Bergsma, W. (2013). A bias-correction for Cramér's V and Tschuprow's T. Journal of the Korean Statistical Society, 42, 323–328.
- Tomczak, M., & Tomczak, E. (2014). The need to report effect size estimates revisited. Trends in Sport Sciences, 21, 19–25.
- Benjamini, Y., & Hochberg, Y. (1995). Controlling the false discovery rate. JRSS B, 57, 289–300.
- Benjamini, Y., & Yekutieli, D. (2001). The control of the false discovery rate in multiple testing under dependency. Annals of Statistics, 29, 1165–1188.
- Hollander, M., & Wolfe, D. A. (1973). Nonparametric Statistical Methods. Wiley.
- Agresti, A. (2007). An Introduction to Categorical Data Analysis (2nd ed.). Wiley.
From the CodeSplash method registry · association.screen v1.0.0.