Skip to content

BMultivariate · multivariate.cca

Canonical correlation analysis (CCA, ridge and kernel CCA)

How strongly are two sets of variables measured on the same rows related, and through which combinations?

Canonical correlation analysis finds pairs of weighted sums — one from each set of variables — that correlate as much as possible, then the next pair uncorrelated with the first, and so on. It reports the canonical correlations with Bartlett's tests, structure correlations (how each variable relates to the pairs), redundancy, a permutation test and the correlation of the first pair on held-out rows. A ridge steadies the weights when variables are many or collinear; kernel CCA finds smooth nonlinear relations.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called canonical correlation, CCA, cancor…

A real result

Example “Lifecycle”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Canonical correlation analysisRecorded · Python and R agreeRecorded 2026-11-21 · 27 values compared
R

Canonical correlation analysis, first canonical r = 0.82, permutation p = .005

First canonical r
0.8248
Permutation p
.005
Held-out r
0.8131

Effect size

  • First canonical correlation 0.8248

Plots

First canonical pairHow do two numeric variables move together?
View data
Canonical variate 1 of pop15, pop75Canonical variate 1 of sr, dpi, ddpi
−0.5625−1.198
−1.472−0.5145
−1.448−1.126
0.64591.176
0.95100.1325
−0.4046−1.626
0.62110.9759
1.1690.5354
1.1571.058
1.1930.5438
−1.238−1.704
1.0911.156
−0.4886−0.6352
−1.459−1.211
−1.111−1.397
−0.87870.0830
1.1841.209
1.3630.9336
−0.3356−0.1509
0.85061.036
−0.8966−0.1069
−1.078−0.5262
−0.3849−0.9454
0.89511.100
−1.337−1.205
−0.2229−0.0090
−1.052−1.059
−0.9879−0.9893
−0.4568−0.3494
1.0030.8928
0.91240.8070
0.81171.344
0.92530.5573
1.1120.7407
−0.58060.2067
−0.19640.3757
0.06110.6193
−0.66520.1675
−1.636−1.818
−1.229−1.628
0.94430.9488
1.0721.268
−1.492−0.4858
−0.7239−2.486
1.1960.3895
1.2380.3188
0.57630.5914
−0.58930.3917
0.62440.5680
1.3281.046
Structure correlationsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
DimensionValueVariableCorrelation with its canonical variate
Dimension 10.98pop15 (first set)0.9830
Dimension 20.18pop15 (first set)0.1837
Dimension 1-0.97pop75 (first set)−0.9698
Dimension 20.24pop75 (first set)0.2439
Dimension 1-0.49sr (second set)−0.4910
Dimension 2-0.86sr (second set)−0.8558
Dimension 1-0.95dpi (second set)−0.9545
Dimension 20.26dpi (second set)0.2637
Dimension 1-0.05ddpi (second set)−0.0473
Dimension 2-0.14ddpi (second set)−0.1408

Assumptions

  • Linear relations — Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them).
  • Multivariate normality (for Bartlett's test) — Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not.
  • Rows per variable — 50 rows for 5 variables (10.0 per variable). Enough for stable weights.

Canonical correlations

DimensionCanonical rr²Wilks Λχ²dfp (dimensions i…k)
10.82480.68030.277159.0436< .001
20.36530.13340.86666.5882.037

Structure correlations: first set with its canonical variates

VariableDimension 1Dimension 2
pop150.98300.1837
pop75−0.96980.2439

Structure correlations: second set with its canonical variates

VariableDimension 1Dimension 2
sr−0.4910−0.8558
dpi−0.95450.2637
ddpi−0.0473−0.1408

Standardized canonical weights: first set

VariableDimension 1Dimension 2
pop150.58372.320
pop75−0.43952.352

Standardized canonical weights: second set

VariableDimension 1Dimension 2
sr−0.2657−1.047
dpi−0.90680.5263
ddpi−0.08380.2465

Variance extracted and redundancy

DimensionFirst set: own variateFirst set: by the other variateSecond set: own variateSecond set: by the other variate
195.3%64.9%38.5%26.2%
24.7%0.6%27.4%3.7%

Held-out correlation of the first pair (5-fold)

FoldHeld-out r
10.7283
20.8361
30.9057
40.9140
50.6811
  • Variables standardized; signs make each dimension's largest first-set structure correlation positive; permutation p for the first correlation from 199 row permutations of the second set (seed 42); held-out r = mean over 5 folds of the first pair's correlation on rows the fit did not see.
Python

Canonical correlation analysis, first canonical r = 0.82, permutation p = .005

First canonical r
0.8248
Permutation p
.005
Held-out r
0.8131

Effect size

  • First canonical correlation 0.8248

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

Assumptions

  • Linear relations — Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them).
  • Multivariate normality (for Bartlett's test) — Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not.
  • Rows per variable — 50 rows for 5 variables (10.0 per variable). Enough for stable weights.

Canonical correlations

DimensionCanonical rr²Wilks Λχ²dfp (dimensions i…k)
10.82480.68030.277159.0436< .001
20.36530.13340.86666.5882.037

Structure correlations: first set with its canonical variates

VariableDimension 1Dimension 2
pop150.98300.1837
pop75−0.96980.2439

Structure correlations: second set with its canonical variates

VariableDimension 1Dimension 2
sr−0.4910−0.8558
dpi−0.95450.2637
ddpi−0.0473−0.1408

Standardized canonical weights: first set

VariableDimension 1Dimension 2
pop150.58372.320
pop75−0.43952.352

Standardized canonical weights: second set

VariableDimension 1Dimension 2
sr−0.2657−1.047
dpi−0.90680.5263
ddpi−0.08380.2465

Variance extracted and redundancy

DimensionFirst set: own variateFirst set: by the other variateSecond set: own variateSecond set: by the other variate
195.3%64.9%38.5%26.2%
24.7%0.6%27.4%3.7%

Held-out correlation of the first pair (5-fold)

FoldHeld-out r
10.7283
20.8361
30.9057
40.9140
50.6811
  • Variables standardized; signs make each dimension's largest first-set structure correlation positive; permutation p for the first correlation from 199 row permutations of the second set (seed 42); held-out r = mean over 5 folds of the first pair's correlation on rows the fit did not see.

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

  • Lifecyclerep2_lifecycle · x_variables: pop15, pop75 · y_variables: sr, dpi, ddpi
  • Lifecycle ridgerep2_lifecycle · x_variables: pop15, pop75 · y_variables: sr, dpi, ddpi
  • Nonlinear linearrep2_nonlinear · x_variables: x1, x2, x3 · y_variables: y1, y2, y3
  • Nonlinear kernelrep2_nonlinear · x_variables: x1, x2, x3 · y_variables: y1, y2, y3
  • Lifecycle linear kernelrep2_lifecycle · x_variables: pop15, pop75 · y_variables: sr, dpi, ddpi
  • Degenerate constantrep2_lifecycle · x_variables: pop15, pop75 · y_variables: sr, dpi, ddpi
  • Degenerate n3rep2_lifecycle · x_variables: pop15, pop75 · y_variables: sr, dpi, ddpi
  • Degenerate same variablerep2_lifecycle · x_variables: pop15, sr · y_variables: sr, dpi

In the guides

Where it sits in the decision guides

  • Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
  • Multiview and multiway structure (CCA, generalized CCA, tensors) · DS & ML Decision Guide · Discover — find structure without labels

What you need

First setnumeric · 1–50 columns
The variables of the first set (rows with a missing value are left out).
Second setnumeric · 1–50 columns
The variables of the second set, measured on the same rows.

Choices you make

model

Methoddefault linear

Linear CCA relates weighted sums; kernel CCA allows smooth nonlinear functions of each set.

  • Linear(default) — Classical canonical correlation analysis (optionally with a ridge).
  • Kernel — Regularized kernel CCA: nonlinear relations; judge it by the held-out correlation.
Ridgedefault 0

Added to each set's correlation matrix; steadies the weights with many or collinear variables (0 = classical CCA).

Kerneldefault rbf

The similarity between rows used in each set.

  • Gaussian (RBF)(default) — exp(−distance² / 2σ²) on standardized variables: smooth nonlinear relations.
  • Linear — Inner products: reproduces ridge CCA with the same regularization (a check).
Bandwidth σdefault 0

RBF width on standardized variables; 0 uses each set's median pairwise distance.

Regularizationdefault 0.1

κ as a multiple of n − 1; larger values give smoother, more stable variates. Needed: without it every kernel correlation is 1.

Dimensionsdefault 2

Kernel canonical pairs to report (linear CCA reports all of them).

hypothesis

Permutationsdefault 999

Row permutations for the test of the first canonical correlation; 0 skips the test.

Permutationsdefault 199

Row permutations for the kernel test (each one solves an n × n problem); 0 skips the test.

Significance leveldefault 0.05

Level used in the narrative.

statistics

Held-out foldsdefault 5

Folds for the first pair's correlation on rows the fit did not see; 0 skips it.

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.

  • Linear relationsNot checked from data: state why it holds

    Linear CCA relates weighted sums and misses curved relations; kernel CCA allows smooth ones.

  • Multivariate normality (for Bartlett's test)Not checked from data: state why it holds

    Bartlett's chi-square tests assume multivariate normal sets; the permutation test does not.

  • Rows per variable

    Below about 10 rows per variable canonical weights are unstable; read structure correlations and the held-out r instead.

What it reports

  • Tests: The two sets are unrelated
n
Number of variables in the first set (p) and the second set (q); CCA has min(p, q) canonical dimensions.
p
Number of variables in the first set (p) and the second set (q); CCA has min(p, q) canonical dimensions.
q
Number of variables in the first set (p) and the second set (q); CCA has min(p, q) canonical dimensions.
k
Finds a weighted sum of each of two sets of variables so the two sums correlate as much as possible, then further uncorrelated pairs.
r1
Finds a weighted sum of each of two sets of variables so the two sums correlate as much as possible, then further uncorrelated pairs.
rho1
The value ridge or kernel CCA maximizes; below the plain correlation of its variates because the penalty shrinks it.
ridge
Amount added to each set's correlation matrix in ridge CCA; steadies weights with many or collinear variables (0 = classical).
reg
κ as a multiple of n − 1 added to each centered kernel; larger values give smoother, more stable variates.
p_perm
Share of row permutations of the second set whose first canonical correlation is at least the observed one; no normality needed.
n_perm
Share of row permutations of the second set whose first canonical correlation is at least the observed one; no normality needed.
cv_r
Correlation of the first canonical pair on rows the fit did not see, averaged over folds; an honest size of the relation.
cv_folds
Correlation of the first canonical pair on rows the fit did not see, averaged over folds; an honest size of the relation.
wilks
χ² test from Wilks' Λ that the canonical correlations from dimension i on are all zero; assumes multivariate normal sets.
chisq
χ² test from Wilks' Λ that the canonical correlations from dimension i on are all zero; assumes multivariate normal sets.
df
χ² test from Wilks' Λ that the canonical correlations from dimension i on are all zero; assumes multivariate normal sets.
p_bartlett
χ² test from Wilks' Λ that the canonical correlations from dimension i on are all zero; assumes multivariate normal sets.
redundancy_x
Share of one set's variance explained by the other set's canonical variates, summed over dimensions (Stewart & Love 1968).
redundancy_y
Share of one set's variance explained by the other set's canonical variates, summed over dimensions (Stewart & Love 1968).
sigma_x
Width σ of the Gaussian kernel on standardized variables; by default each set's median pairwise distance.
sigma_y
Width σ of the Gaussian kernel on standardized variables; by default each set's median pairwise distance.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: r[<k>], rho[<k>], p_dim[<k>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the codesplash twins: eigen inverse square roots, SVD of the whitened cross-correlation, the same sign rule and the shared Wichmann–Hill folds and permutations, so every number matches. stats::cancor gives the same canonical correlations (checked in tests/crosscheck/w5_rep2.R); sklearn's NIPALS CCA scales the weights differently.
  • Kernel CCA uses κ = reg × (n − 1) on centered kernels, so the linear kernel reproduces ridge CCA with ridge = reg exactly (checked in the crosscheck); kernlab::kcca regularizes differently.
Python

The exact script CodeSplash ran for example “Lifecycle” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Canonical correlation analysis (CCA, ridge and kernel CCA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.cca 1.0.0 · spec 08dfc48621ffa8b6
# Dataset: rep2_lifecycle (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.errors import check_groups, check_not_constant
from codesplash.stats import multiview as mvw

# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_lifecycle.parquet", columns=["pop15", "pop75", "sr", "dpi", "ddpi"])
n_input = len(df)
df = df.dropna(subset=["pop15", "pop75", "sr", "dpi", "ddpi"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["pop15", "pop75", "sr", "dpi", "ddpi"])  # infinite values stop the run (registry/errors.yaml)

# %% Analysis
# Canonical correlation analysis (Hotelling 1936): pairs of weighted sums, one per set, that correlate as
# much as possible. Linear CCA (optional ridge, Vinod 1976) or regularized kernel CCA (Hardoon et al. 2004).
x_vars = ["pop15", "pop75"]
y_vars = ["sr", "dpi", "ddpi"]
method = "linear"  # linear | kernel
ridge = float(0)
kernel_type = "rbf"  # rbf | linear
bandwidth = float(0)
reg = float(0.1)
n_comp = int(2)
n_perm = int(199) if method == "linear" else int(199)
cv_folds = int(5)
alpha = 0.05
seed = 42
both = [v for v in x_vars if v in y_vars]
if both:
    cs.cs_error("CS_E_INVALID_OPTION", option="The two sets", allowed="separate variables (none in both sets)", value=both[0])
n = len(df)
p, q = len(x_vars), len(y_vars)
cs.check_rows(n, p + q + 2 if method == "linear" and ridge == 0 else 5, "Canonical correlation analysis")
for v in x_vars + y_vars:
    check_not_constant(df[v], v)
if method == "kernel" and n > 2000:
    cs.cs_error("CS_E_UNDEFINED", what="Kernel CCA", reason=f"it uses n × n kernel matrices; {n} rows is too many (at most 2,000)")
X = df[x_vars].to_numpy(dtype=float)
Y = df[y_vars].to_numpy(dtype=float)

if method == "linear":
    fit = mvw.cca(X, Y, ridge)
    k = fit["k"]
    r, rho = fit["r"], fit["rho"]
    u, v = fit["u"][:, 0], fit["v"][:, 0]
    struct_x, struct_y = fit["struct_x"], fit["struct_y"]
    bart = mvw.bartlett(r, n, p, q) if ridge == 0 else None
else:
    fit = mvw.kcca(X, Y, kernel_type, reg, n_comp, bandwidth)
    k = len(fit["rho"])
    r, rho = fit["r_train"], fit["rho"]
    u, v = fit["F"][:, 0], fit["G"][:, 0]
    u, v = (u - u.mean()) / u.std(ddof=1), (v - v.mean()) / v.std(ddof=1)
    struct_x, struct_y = fit["struct_x"], fit["struct_y"]
    bart = None
perm = None
if n_perm > 0:
    perm = (mvw.cca_permutation(X, Y, ridge, n_perm, seed) if method == "linear"
            else mvw.kcca_permutation(X, Y, kernel_type, reg, bandwidth, n_perm, seed))
cv = None
if cv_folds >= 2:
    cv = (mvw.cca_cv(X, Y, ridge, cv_folds, seed) if method == "linear"
          else mvw.kcca_cv(X, Y, kernel_type, reg, bandwidth, cv_folds, seed))

# %% Assumptions
ratio = n / (p + q)
assumptions = [
    {"key": "linear", "label": "Linear relations" if method == "linear" else "Smooth relations (kernel)", "status": "info",
     "detail": ("Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them)."
                if method == "linear" else "The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation.")},
    {"key": "normality", "label": "Multivariate normality (for Bartlett's test)", "status": "info",
     "detail": "Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not." if bart is not None
               else "No normal-theory test is reported here; the permutation p only assumes exchangeable rows."},
    {"key": "rows_per_variable", "label": "Rows per variable", "status": "ok" if ratio >= 10 else "warn",
     "detail": f"{n} rows for {p + q} variables ({ratio:.1f} per variable). " + ("Enough for stable weights." if ratio >= 10
               else "Canonical weights and correlations are unstable below about 10 rows per variable; trust the held-out correlation and structure correlations more than the weights.")},
]

# %% Result
values = {"n": n, "p": p, "q": q, "k": k, "r1": float(r[0]), "rho1": float(rho[0]),
          "ridge": ridge if method == "linear" else float("nan"), "reg": reg if method == "kernel" else float("nan"),
          "p_perm": perm["p"] if perm else float("nan"), "n_perm": n_perm if perm else 0,
          "cv_r": cv["mean"] if cv else float("nan"), "cv_folds": cv_folds if cv else 0,
          "wilks": bart[0]["wilks"] if bart else float("nan"), "chisq": bart[0]["chisq"] if bart else float("nan"),
          "df": bart[0]["df"] if bart else float("nan"), "p_bartlett": bart[0]["p"] if bart else float("nan"),
          "redundancy_y": float(np.sum(fit["redundancy_y"])) if method == "linear" else float("nan"),
          "redundancy_x": float(np.sum(fit["redundancy_x"])) if method == "linear" else float("nan"),
          "sigma_x": fit["sigma_x"] if method == "kernel" and kernel_type == "rbf" else float("nan"),
          "sigma_y": fit["sigma_y"] if method == "kernel" and kernel_type == "rbf" else float("nan")}
for j in range(k):
    values[f"r[{j + 1}]"] = float(r[j])
    values[f"rho[{j + 1}]"] = float(rho[j])
    if bart:
        values[f"p_dim[{j + 1}]"] = bart[j]["p"]
values["missing_share"] = n_dropped / n_input if n_input else 0.0

cols = [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "r", "label": "Canonical r", "type": "number"},
        {"key": "r2", "label": "r²", "type": "number"}]
if method == "kernel" or ridge > 0:
    cols.append({"key": "rho", "label": "Regularized ρ", "type": "number"})
if bart:
    cols += [{"key": "wilks", "label": "Wilks Λ", "type": "number"}, {"key": "chisq", "label": "χ²", "type": "number"},
             {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p (dimensions i…k)", "type": "pvalue"}]
rows = []
for j in range(k):
    row = {"dimension": j + 1, "r": float(r[j]), "r2": float(r[j] ** 2), "rho": float(rho[j])}
    if bart:
        row.update({"wilks": bart[j]["wilks"], "chisq": bart[j]["chisq"], "df": bart[j]["df"], "p": bart[j]["p"]})
    rows.append(row)
tables = [{"key": "canonical", "title": "Canonical correlations", "columns": cols, "rows": rows}]


def struct_table(key, title, names, M):
    return {"key": key, "title": title,
            "columns": [{"key": "variable", "label": "Variable", "type": "string"}]
                       + [{"key": f"d{j + 1}", "label": f"Dimension {j + 1}", "type": "number"} for j in range(k)],
            "rows": [{"variable": nm, **{f"d{j + 1}": float(M[i, j]) for j in range(k)}} for i, nm in enumerate(names)]}


tables.append(struct_table("structure_x", "Structure correlations: first set with its canonical variates", x_vars, struct_x))
tables.append(struct_table("structure_y", "Structure correlations: second set with its canonical variates", y_vars, struct_y))
if method == "linear":
    tables.append(struct_table("coef_x", "Standardized canonical weights: first set", x_vars, fit["coef_x"]))
    tables.append(struct_table("coef_y", "Standardized canonical weights: second set", y_vars, fit["coef_y"]))
    tables.append({"key": "redundancy", "title": "Variance extracted and redundancy",
                   "columns": [{"key": "dimension", "label": "Dimension", "type": "integer"},
                               {"key": "extracted_x", "label": "First set: own variate", "type": "percent"},
                               {"key": "redundancy_x", "label": "First set: by the other variate", "type": "percent"},
                               {"key": "extracted_y", "label": "Second set: own variate", "type": "percent"},
                               {"key": "redundancy_y", "label": "Second set: by the other variate", "type": "percent"}],
                   "rows": [{"dimension": j + 1, "extracted_x": float(fit["extracted_x"][j]), "redundancy_x": float(fit["redundancy_x"][j]),
                             "extracted_y": float(fit["extracted_y"][j]), "redundancy_y": float(fit["redundancy_y"][j])} for j in range(k)]})
if cv:
    tables.append({"key": "cv", "title": f"Held-out correlation of the first pair ({cv_folds}-fold)",
                   "columns": [{"key": "fold", "label": "Fold", "type": "integer"}, {"key": "r", "label": "Held-out r", "type": "number"}],
                   "rows": [{"fold": i + 1, "r": float(x)} for i, x in enumerate(cv["folds"])]})

xs, ys = ", ".join(x_vars), ", ".join(y_vars)
charts = [cs.chart("pair", "scatter", "First canonical pair", {
    "x": cs.col(f"Canonical variate 1 of {xs}", u),
    "y": cs.col(f"Canonical variate 1 of {ys}", v)})]
heat_rows, heat_cols, heat_vals = [], [], []
for names, M, side in ((x_vars, struct_x, "first"), (y_vars, struct_y, "second")):
    for i, nm in enumerate(names):
        for j in range(k):
            heat_rows.append(f"{nm} ({side} set)")
            heat_cols.append(f"Dimension {j + 1}")
            heat_vals.append(float(M[i, j]))
charts.append(cs.chart("structure", "matrix-heatmap", "Structure correlations", {
    "row": cs.col("Variable", heat_rows, "categorical"),
    "col": cs.col("Dimension", heat_cols, "categorical"),
    "value": cs.col("Correlation with its canonical variate", np.array(heat_vals)),
    "label": cs.col("Value", [f"{x:.2f}" for x in heat_vals], "categorical")}))

label = "Kernel CCA" if method == "kernel" else ("Ridge CCA" if ridge > 0 else "Canonical correlation analysis")
sig = perm is not None and perm["p"] < alpha
summary = (f"{label} of {xs} with {ys} ({n} rows): the first canonical correlation is r = {r[0]:.3f}"
           + (f", {cs.fmt_p(perm['p'])} by {n_perm} permutations" if perm else "")
           + (f"; on held-out rows the first pair correlates r = {cv['mean']:.3f} ({cv_folds}-fold)" if cv else "") + ". "
           + ("The two sets share a linear relation." if sig and method == "linear" else "The two sets are related." if sig
              else "No evidence that the sets are related." if perm else ""))
cs.publish({
    "method": "multivariate.cca",
    "methodVersion": "1.0.0",
    "title": label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary.strip(),
    "apa": f"{label}, first canonical r = {r[0]:.2f}" + (f", permutation {cs.fmt_p(perm['p'])}" if perm else ""),
    "statistics": [{"key": "r1", "label": "First canonical r", "value": float(r[0])},
                   {"key": "p_perm", "label": "Permutation p", "value": values["p_perm"], "format": "p"},
                   {"key": "cv_r", "label": "Held-out r", "value": values["cv_r"]}],
    "tables": tables,
    "effectSizes": [{"key": "r1", "label": "First canonical correlation", "value": float(r[0]), "method": "Correlation of the first pair of canonical variates"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [("Variables standardized; " + (f"ridge {ridge:g} added to each set's correlation matrix (regularized ρ is the maximized criterion, r the correlation of the resulting variates); " if method == "linear" and ridge > 0 else "")
               + (f"kernel {kernel_type}" + (f", bandwidths {fit['sigma_x']:.3g} and {fit['sigma_y']:.3g} (median distance)" if kernel_type == "rbf" and bandwidth == 0 else "")
                  + f", regularization κ = {reg:g} × (n − 1); " if method == "kernel" else "")
               + "signs make each dimension's largest first-set structure correlation positive"
               + (f"; permutation p for the first correlation from {n_perm} row permutations of the second set (seed {seed})" if perm else "")
               + (f"; held-out r = mean over {cv_folds} folds of the first pair's correlation on rows the fit did not see" if cv else "") + ".")],
    "values": values,
    "charts": charts,
})
R

The exact script CodeSplash ran for example “Lifecycle” · R version 4.5.1 (2025-06-13)

# Canonical correlation analysis (CCA, ridge and kernel CCA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.cca 1.0.0 · spec 08dfc48621ffa8b6
# Dataset: rep2_lifecycle (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_lifecycle.parquet", col_select = c("pop15", "pop75", "sr", "dpi", "ddpi")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("pop15", "pop75", "sr", "dpi", "ddpi")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("pop15", "pop75", "sr", "dpi", "ddpi"))  # infinite values stop the run (registry/errors.yaml)

# %% Analysis
# Canonical correlation analysis (Hotelling 1936): pairs of weighted sums, one per set, that correlate as
# much as possible. Linear CCA (optional ridge, Vinod 1976) or regularized kernel CCA (Hardoon et al. 2004).
x_vars <- c("pop15", "pop75")
y_vars <- c("sr", "dpi", "ddpi")
method <- "linear"  # linear | kernel
ridge <- as.numeric(0)
kernel_type <- "rbf"  # rbf | linear
bandwidth <- as.numeric(0)
reg <- as.numeric(0.1)
n_comp <- as.integer(2)
n_perm <- if (method == "linear") as.integer(199) else as.integer(199)
cv_folds <- as.integer(5)
alpha <- 0.05
seed <- 42
both <- x_vars[x_vars %in% y_vars]
if (length(both)) cs_error("CS_E_INVALID_OPTION", option = "The two sets", allowed = "separate variables (none in both sets)", value = both[1])
n <- nrow(df)
p <- length(x_vars)
q <- length(y_vars)
cs_check_rows(n, if (method == "linear" && ridge == 0) p + q + 2 else 5, "Canonical correlation analysis")
for (v in c(x_vars, y_vars)) cs_check_not_constant(df[[v]], v)
if (method == "kernel" && n > 2000) {
  cs_error("CS_E_UNDEFINED", what = "Kernel CCA", reason = sprintf("it uses n × n kernel matrices; %d rows is too many (at most 2,000)", n))
}
X <- as.matrix(df[x_vars])
Y <- as.matrix(df[y_vars])
storage.mode(X) <- "double"
storage.mode(Y) <- "double"

if (method == "linear") {
  fit <- cs_mview_cca(X, Y, ridge)
  k <- fit$k
  r <- fit$r
  rho <- fit$rho
  u <- fit$u[, 1]
  v <- fit$v[, 1]
  struct_x <- fit$struct_x
  struct_y <- fit$struct_y
  bart <- if (ridge == 0) cs_mview_bartlett(r, n, p, q) else NULL
} else {
  fit <- cs_mview_kcca(X, Y, kernel_type, reg, n_comp, bandwidth)
  k <- length(fit$rho)
  r <- fit$r_train
  rho <- fit$rho
  u <- fit$F[, 1]
  v <- fit$G[, 1]
  u <- (u - mean(u)) / stats::sd(u)
  v <- (v - mean(v)) / stats::sd(v)
  struct_x <- fit$struct_x
  struct_y <- fit$struct_y
  bart <- NULL
}
perm <- NULL
if (n_perm > 0) {
  perm <- if (method == "linear") cs_mview_cca_permutation(X, Y, ridge, n_perm, seed)
          else cs_mview_kcca_permutation(X, Y, kernel_type, reg, bandwidth, n_perm, seed)
}
cv <- NULL
if (cv_folds >= 2) {
  cv <- if (method == "linear") cs_mview_cca_cv(X, Y, ridge, cv_folds, seed)
        else cs_mview_kcca_cv(X, Y, kernel_type, reg, bandwidth, cv_folds, seed)
}

# %% Assumptions
ratio <- n / (p + q)
assumptions <- list(
  list(key = "linear", label = if (method == "linear") "Linear relations" else "Smooth relations (kernel)", status = "info",
       detail = if (method == "linear") "Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them)."
                else "The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation."),
  list(key = "normality", label = "Multivariate normality (for Bartlett's test)", status = "info",
       detail = if (!is.null(bart)) "Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not."
                else "No normal-theory test is reported here; the permutation p only assumes exchangeable rows."),
  list(key = "rows_per_variable", label = "Rows per variable", status = if (ratio >= 10) "ok" else "warn",
       detail = paste0(sprintf("%d rows for %d variables (%.1f per variable). ", n, p + q, ratio),
                       if (ratio >= 10) "Enough for stable weights."
                       else "Canonical weights and correlations are unstable below about 10 rows per variable; trust the held-out correlation and structure correlations more than the weights."))
)

# %% Result
nan_or <- function(cond, x) if (cond) x else NaN
values <- list(n = n, p = p, q = q, k = k, r1 = r[1], rho1 = rho[1],
               ridge = nan_or(method == "linear", ridge), reg = nan_or(method == "kernel", reg),
               p_perm = if (!is.null(perm)) perm$p else NaN, n_perm = if (!is.null(perm)) n_perm else 0L,
               cv_r = if (!is.null(cv)) cv$mean else NaN, cv_folds = if (!is.null(cv)) cv_folds else 0L,
               wilks = if (!is.null(bart)) bart[[1]]$wilks else NaN, chisq = if (!is.null(bart)) bart[[1]]$chisq else NaN,
               df = if (!is.null(bart)) bart[[1]]$df else NaN, p_bartlett = if (!is.null(bart)) bart[[1]]$p else NaN,
               redundancy_y = nan_or(method == "linear", sum(fit$redundancy_y)),
               redundancy_x = nan_or(method == "linear", sum(fit$redundancy_x)),
               sigma_x = nan_or(method == "kernel" && kernel_type == "rbf", fit$sigma_x),
               sigma_y = nan_or(method == "kernel" && kernel_type == "rbf", fit$sigma_y))
for (j in seq_len(k)) {
  values[[sprintf("r[%d]", j)]] <- r[j]
  values[[sprintf("rho[%d]", j)]] <- rho[j]
  if (!is.null(bart)) values[[sprintf("p_dim[%d]", j)]] <- bart[[j]]$p
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0

cols <- list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "r", label = "Canonical r", type = "number"),
             list(key = "r2", label = "r²", type = "number"))
if (method == "kernel" || ridge > 0) cols <- c(cols, list(list(key = "rho", label = "Regularized ρ", type = "number")))
if (!is.null(bart)) {
  cols <- c(cols, list(list(key = "wilks", label = "Wilks Λ", type = "number"), list(key = "chisq", label = "χ²", type = "number"),
                       list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p (dimensions i…k)", type = "pvalue")))
}
rows <- lapply(seq_len(k), function(j) {
  row <- list(dimension = j, r = r[j], r2 = r[j]^2, rho = rho[j])
  if (!is.null(bart)) row <- c(row, list(wilks = bart[[j]]$wilks, chisq = bart[[j]]$chisq, df = bart[[j]]$df, p = bart[[j]]$p))
  row
})
tables <- list(list(key = "canonical", title = "Canonical correlations", columns = cols, rows = rows))
struct_table <- function(key, title, names, M) {
  list(key = key, title = title,
       columns = c(list(list(key = "variable", label = "Variable", type = "string")),
                   lapply(seq_len(k), function(j) list(key = sprintf("d%d", j), label = sprintf("Dimension %d", j), type = "number"))),
       rows = lapply(seq_along(names), function(i) {
         row <- list(variable = names[i])
         for (j in seq_len(k)) row[[sprintf("d%d", j)]] <- M[i, j]
         row
       }))
}
tables[[length(tables) + 1]] <- struct_table("structure_x", "Structure correlations: first set with its canonical variates", x_vars, struct_x)
tables[[length(tables) + 1]] <- struct_table("structure_y", "Structure correlations: second set with its canonical variates", y_vars, struct_y)
if (method == "linear") {
  tables[[length(tables) + 1]] <- struct_table("coef_x", "Standardized canonical weights: first set", x_vars, fit$coef_x)
  tables[[length(tables) + 1]] <- struct_table("coef_y", "Standardized canonical weights: second set", y_vars, fit$coef_y)
  tables[[length(tables) + 1]] <- list(key = "redundancy", title = "Variance extracted and redundancy",
    columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
                   list(key = "extracted_x", label = "First set: own variate", type = "percent"),
                   list(key = "redundancy_x", label = "First set: by the other variate", type = "percent"),
                   list(key = "extracted_y", label = "Second set: own variate", type = "percent"),
                   list(key = "redundancy_y", label = "Second set: by the other variate", type = "percent")),
    rows = lapply(seq_len(k), function(j) list(dimension = j, extracted_x = fit$extracted_x[j], redundancy_x = fit$redundancy_x[j],
                                               extracted_y = fit$extracted_y[j], redundancy_y = fit$redundancy_y[j])))
}
if (!is.null(cv)) {
  tables[[length(tables) + 1]] <- list(key = "cv", title = sprintf("Held-out correlation of the first pair (%d-fold)", cv_folds),
    columns = list(list(key = "fold", label = "Fold", type = "integer"), list(key = "r", label = "Held-out r", type = "number")),
    rows = lapply(seq_along(cv$folds), function(i) list(fold = i, r = cv$folds[i])))
}

xs <- paste(x_vars, collapse = ", ")
ys <- paste(y_vars, collapse = ", ")
charts <- list(cs_chart("pair", "scatter", "First canonical pair", list(
  x = cs_col(sprintf("Canonical variate 1 of %s", xs), u),
  y = cs_col(sprintf("Canonical variate 1 of %s", ys), v))))
heat_rows <- character(0); heat_cols <- character(0); heat_vals <- numeric(0)
for (side in list(list(x_vars, struct_x, "first"), list(y_vars, struct_y, "second"))) {
  for (i in seq_along(side[[1]])) {
    for (j in seq_len(k)) {
      heat_rows <- c(heat_rows, sprintf("%s (%s set)", side[[1]][i], side[[3]]))
      heat_cols <- c(heat_cols, sprintf("Dimension %d", j))
      heat_vals <- c(heat_vals, side[[2]][i, j])
    }
  }
}
charts[[2]] <- cs_chart("structure", "matrix-heatmap", "Structure correlations", list(
  row = cs_col("Variable", heat_rows, "categorical"),
  col = cs_col("Dimension", heat_cols, "categorical"),
  value = cs_col("Correlation with its canonical variate", heat_vals),
  label = cs_col("Value", sprintf("%.2f", heat_vals), "categorical")))

label <- if (method == "kernel") "Kernel CCA" else if (ridge > 0) "Ridge CCA" else "Canonical correlation analysis"
sig <- !is.null(perm) && perm$p < alpha
summary <- paste0(sprintf("%s of %s with %s (%d rows): the first canonical correlation is r = %.3f", label, xs, ys, n, r[1]),
                  if (!is.null(perm)) sprintf(", %s by %d permutations", cs_fmt_p(perm$p), n_perm) else "",
                  if (!is.null(cv)) sprintf("; on held-out rows the first pair correlates r = %.3f (%d-fold)", cv$mean, cv_folds) else "", ". ",
                  if (sig && method == "linear") "The two sets share a linear relation." else if (sig) "The two sets are related."
                  else if (!is.null(perm)) "No evidence that the sets are related." else "")
note <- paste0("Variables standardized; ",
               if (method == "linear" && ridge > 0) sprintf("ridge %s added to each set's correlation matrix (regularized ρ is the maximized criterion, r the correlation of the resulting variates); ", format(ridge)) else "",
               if (method == "kernel") paste0(sprintf("kernel %s", kernel_type),
                                             if (kernel_type == "rbf" && bandwidth == 0) sprintf(", bandwidths %s and %s (median distance)", format(signif(fit$sigma_x, 3)), format(signif(fit$sigma_y, 3))) else "",
                                             sprintf(", regularization κ = %s × (n − 1); ", format(reg))) else "",
               "signs make each dimension's largest first-set structure correlation positive",
               if (!is.null(perm)) sprintf("; permutation p for the first correlation from %d row permutations of the second set (seed %d)", n_perm, as.integer(seed)) else "",
               if (!is.null(cv)) sprintf("; held-out r = mean over %d folds of the first pair's correlation on rows the fit did not see", cv_folds) else "", ".")
cs_publish(list(
  method = "multivariate.cca",
  methodVersion = "1.0.0",
  title = label,
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = trimws(summary),
  apa = paste0(sprintf("%s, first canonical r = %.2f", label, r[1]), if (!is.null(perm)) sprintf(", permutation %s", cs_fmt_p(perm$p)) else ""),
  statistics = list(list(key = "r1", label = "First canonical r", value = r[1]),
                    list(key = "p_perm", label = "Permutation p", value = values$p_perm, format = "p"),
                    list(key = "cv_r", label = "Held-out r", value = values$cv_r)),
  tables = tables,
  effectSizes = list(list(key = "r1", label = "First canonical correlation", value = r[1], method = "Correlation of the first pair of canonical variates")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(note),
  values = values,
  charts = charts
))

Sources

  • Hotelling, H. (1936). Relations between two sets of variates. Biometrika, 28, 321–377.
  • Bartlett, M. S. (1938). Further aspects of the theory of multiple regression. Proc. Cambridge Philosophical Society, 34, 33–40.
  • Stewart, D., & Love, W. (1968). A general canonical correlation index. Psychological Bulletin, 70, 160–163.
  • Vinod, H. D. (1976). Canonical ridge and econometrics of joint production. Journal of Econometrics, 4, 147–166.
  • Hardoon, D. R., Szedmak, S., & Shawe-Taylor, J. (2004). Canonical correlation analysis: an overview with application to learning methods. Neural Computation, 16, 2639–2664.

From the CodeSplash method registry · multivariate.cca v1.0.0.