Skip to content

GQuality & process · doe.analyze

Analyze a two-level factorial experiment (effects, Lenth, ANOVA)

Which factors and interactions change the response, and by how much?

Estimates main effects and interactions of a two-level full or fractional factorial (or screening) experiment in coded units, with Lenth's pseudo standard error for unreplicated designs, a center-point curvature test, a sequential ANOVA with lack of fit, aliased terms identified, and Pareto, half-normal, main-effect and interaction plots.

Verified in Python and R Python and R agree to 10 decimals

A real result

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

Analyze a two-level factorial experiment (effects, Lenth, ANOVA)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

5 of 10 effects stand out (Temperature, Formaldehyde (%), Stirring, Temperature × Formaldehyde (%), Temperature × Stirring) at α = 0.05.

Runs
16
Center runs
0
Residual df
5
R²
0.9777
S
5.056

Plots

Pareto chart of effectsWhich effects are largest, and which exceed Lenth's margin of error?
View data
Term|t|
Temperature8.554
Temperature × Formaldehyde (%)7.170
Temperature × Stirring6.576
Stirring5.785
Formaldehyde (%)3.906
Pressure1.236
Pressure × Formaldehyde (%)0.9395
Formaldehyde (%) × Stirring0.4450
Pressure × Stirring0.1483
Temperature × Pressure0.0494
Half-normal plot of effectsWhich factor effects in an unreplicated factorial stand out from noise?
View data
|Effect|TermHalf-normal quantileSignificant
0.1250Temperature × Pressure0.0627false
0.3750Pressure × Stirring0.1891false
1.125Formaldehyde (%) × Stirring0.3186false
2.375Pressure × Formaldehyde (%)0.4538false
3.125Pressure0.5978false
9.875Formaldehyde (%)0.7554true
14.625Stirring0.9346true
16.625Temperature × Stirring1.150true
18.125Temperature × Formaldehyde (%)1.440true
21.625Temperature1.960true
Main effects (mean response at each level)How does the mean response change across each factor's levels?
View data
FactorLevelMean Filtration rate
Temperature24.0059.250
Temperature35.0080.875
Pressure10.0068.500
Pressure15.0071.625
Formaldehyde (%)2.0065.125
Formaldehyde (%)4.0075
Stirringslow62.750
Stirringfast77.375
Interaction: Temperature × Formaldehyde (%)Does the effect of one factor depend on another?
View data
Formaldehyde (%)TemperatureFiltration rate
2.0024.0045
2.0035.0071
2.0024.0048
2.0035.0065
4.0024.0068
4.0035.0060
4.0024.0080
4.0035.0065
2.0024.0043
2.0035.00100
2.0024.0045
2.0035.00104
4.0024.0075
4.0035.0086
4.0024.0070
4.0035.0096
Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
Fitted valuesResiduals
45.188−0.1875
68.1882.813
46.1881.812
69.438−4.438
71.938−3.938
58.6881.313
77.6882.313
64.6880.3125
44.688−1.688
100.94−0.9375
44.9380.0625
101.442.563
69.1885.813
89.188−3.188
74.188−4.188
94.4381.563

Effects and coefficients (coded units)

TermEffectCoefficientSEtp
(Intercept)—70.0631.26455.430< .001
Temperature21.62510.8131.2648.554< .001
Pressure3.1251.5631.2641.236.271
Formaldehyde (%)9.8754.9381.2643.906.011
Stirring14.6257.3131.2645.785.002
Temperature × Pressure0.12500.06251.2640.0494.962
Temperature × Formaldehyde (%)−18.125−9.0631.264−7.170< .001
Temperature × Stirring16.6258.3131.2646.576.001
Pressure × Formaldehyde (%)2.3751.1881.2640.9395.391
Pressure × Stirring−0.3750−0.18751.264−0.1483.888
Formaldehyde (%) × Stirring−1.125−0.56251.264−0.4450.675

Analysis of variance (sequential)

SourcedfSSMSFp
Main effects43155.25788.8130.858.001
2-way interactions62447.88407.9815.960.004
Residual error5127.8125.563——
Total155730.94———

Factor coding

FactorLow (−1)High (+1)Center (0)
Temperature24.0035.0029.50
Pressure10.0015.0012.50
Formaldehyde (%)2.004.003.00
Stirringslowfast—
  • Effects are differences between the high and low settings (2 × the coded coefficient).
Python

5 of 10 effects stand out (Temperature, Formaldehyde (%), Stirring, Temperature × Formaldehyde (%), Temperature × Stirring) at α = 0.05.

Runs
16
Center runs
0
Residual df
5
R²
0.9777
S
5.056

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

Effects and coefficients (coded units)

TermEffectCoefficientSEtp
(Intercept)—70.0631.26455.430< .001
Temperature21.62510.8121.2648.554< .001
Pressure3.1251.5621.2641.236.271
Formaldehyde (%)9.8754.9371.2643.906.011
Stirring14.6257.3121.2645.785.002
Temperature × Pressure0.12500.06251.2640.0494.962
Temperature × Formaldehyde (%)−18.125−9.0631.264−7.170< .001
Temperature × Stirring16.6258.3131.2646.576.001
Pressure × Formaldehyde (%)2.3751.1881.2640.9395.391
Pressure × Stirring−0.3750−0.18751.264−0.1483.888
Formaldehyde (%) × Stirring−1.125−0.56251.264−0.4450.675

Analysis of variance (sequential)

SourcedfSSMSFp
Main effects43155.25788.8130.858.001
2-way interactions62447.88407.9815.960.004
Residual error5127.8125.562——
Total155730.94———

Factor coding

FactorLow (−1)High (+1)Center (0)
Temperature24.0035.0029.50
Pressure10.0015.0012.50
Formaldehyde (%)2.004.003.00
Stirringslowfast—
  • Effects are differences between the high and low settings (2 × the coded coefficient).

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

  • Filtration unreplicatedq1_filtration · factors: Temperature, Pressure, Formaldehyde (%), Stirring · response: Filtration rate
  • Filtration three wayq1_filtration · factors: Temperature, Formaldehyde (%), Stirring · response: Filtration rate
  • Fraction centre blocksq1_fraction · block: Day · factors: Speed, Feed, Depth, Coolant, Angle · response: Surface quality
  • Numeric blockq1_fraction · block: Batch · factors: Speed, Feed, Depth · response: Surface quality
  • Main effects onlyq1_fraction · factors: Speed, Feed, Depth · response: Surface quality
  • Degenerate constantq1_filtration · factors: Temperature, Pressure, Formaldehyde (%), Stirring · response: Filtration rate
  • Degenerate n1q1_filtration · factors: Temperature, Pressure, Formaldehyde (%), Stirring · response: Filtration rate
  • Degenerate single levelq1_filtration · factors: Temperature, Pressure, Formaldehyde (%), Stirring · response: Filtration rate

In the guides

Where it sits in the decision guides

  • Statistical optimization (regression, response surface) · DS & ML Decision Guide · Optimize / decide

What you need

Responsenumeric · 1 column
The measured outcome of each run.
Factorsnumeric / categorical / boolean · 1–15 columns
Two-level factors: numeric with two settings (a third, middle setting marks center runs) or categorical with two levels (the first stored level is low).
Blockcategorical / numeric · 0–1 column
Optional blocking variable (days, batches); fitted before the factor effects.

Choices you make

hypothesis

Highest interaction orderdefault 2

1 = main effects only, 2 = with two-factor interactions, … Terms the design aliases with earlier ones are dropped and listed.

Significance level (α)default 0.05

The false-alarm rate you accept: the chance of a significant result when there is truly no effect. 0.05 is conventional.

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.

  • Normal residuals

    Residual normal plot; unreplicated designs rely on effect sparsity (Lenth's method) instead.

  • Constant variance

    Residuals vs fitted values should show no funnel.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_center
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
df_resid
How much independent information is left to estimate variability after fitting the model.
terms
Names of the fitted model's terms, intercept first, in the same order as the list of coefficients.
coef
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
effect_terms
The average effect of one factor across the levels of the others.
effects
The average effect of one factor across the levels of the others.
effect_p
How surprising your data would be if the null hypothesis were true, as a probability.
lenth_pse
Judges effects in an unreplicated factorial by treating the many small ones as an estimate of noise.
lenth_me
Judges effects in an unreplicated factorial by treating the many small ones as an estimate of noise.
lenth_sme
Judges effects in an unreplicated factorial by treating the many small ones as an estimate of noise.
r2
The share of the outcome's variance explained by the model, from 0 to 1.
adj_r2
R² penalized for the number of predictors, so adding useless ones lowers it.
s
A rank test of whether a series tends to rise (or fall) over time — S counts later values above earlier ones minus those below.
curvature_p
How surprising your data would be if the null hypothesis were true, as a probability.
aliases
A subset of a factorial's runs that trades some interactions for far fewer runs; resolution says which effects get mixed up.
significant
A p-value below the chosen α; it says the data are hard to explain by chance alone, not that the effect matters.
n_significant
How many independent units the analysis used; it sets precision and power.
n_effects
Number of main effects and interactions the factorial analysis estimated.
significant_text
The effects judged significant, listed by name for the summary; empty when none are.

Python and R

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

Default traps between the two languages

  • Coefficients from numpy QR least squares ↔ R lm() on the same coded columns; aliasing decided by one Gram–Schmidt twin so both engines keep the same terms.
Python

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

# Analyze a two-level factorial experiment (effects, Lenth, ANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.analyze 1.0.1 · spec 6522775f4b2584ee
# Dataset: q1_filtration (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.quality import analyze as qa  # twin of codesplashr::cs_doe_analyze (coding, aliasing, Lenth)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/q1_filtration.parquet", columns=["Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring"])
n_input = len(df)
df["Stirring"] = pd.Categorical(df["Stirring"], categories=["slow", "fast"])  # stored level order
df = df.dropna(subset=["Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring"])  # listwise deletion over the analysis columns
df["Stirring"] = df["Stirring"].cat.remove_unused_categories()
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, ["Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring"])  # infinite values stop the run (registry/errors.yaml)

# %% Coding (low = −1, high = +1, center runs = 0)
y_name = "Filtration rate"
FACTORS = ["Temperature", "Pressure", "Formaldehyde (%)", "Stirring"]
KINDS = ["numeric", "numeric", "numeric", "categorical", ]
block_col = None
y = df[y_name].to_numpy(dtype=float)
coded_cols, coding, numeric = [], [], []
for f, kind in zip(FACTORS, KINDS):
    if kind in ("categorical", "boolean"):
        c, info = qa.code_factor(df[f].astype(str).tolist(), kind, [str(x) for x in df[f].cat.categories], f)
    else:
        c, info = qa.code_factor(df[f].to_numpy(dtype=float), kind, None, f)
    coded_cols.append(c)
    coding.append(info)
    numeric.append(kind == "numeric")
coded = np.column_stack(coded_cols)
if len(np.unique(y)) < 2:  # a constant response has no effects to estimate
    cs.cs_error("CS_E_CONSTANT", column=y_name)
def _label(v):
    return str(int(v)) if isinstance(v, float) and v.is_integer() else str(v)


block = [_label(v) for v in df[block_col]] if block_col else None  # numeric blocks labeled like R's as.character()
alpha = 0.05

# %% Model: effects in coded units; aliased terms dropped
res = qa.analyze(y, coded, FACTORS, numeric, order=2, block=block, alpha=alpha)
# Classic idiom: statsmodels.formula.api.ols("y ~ (A + B + C)**2", coded data) — the twin fits the same
# least-squares model on the retained columns and drops aliased terms the same way as the R twin.
fit_terms = res["terms"]
df_resid = res["df_resid"]
lenth = res["lenth"]
eff = np.asarray(res["effects"])
eff_terms = res["effect_terms"]
if df_resid > 0:
    sig = [t for t, p in zip(eff_terms, res["effect_p"]) if p < alpha]
else:
    sig = [t for t, e in zip(eff_terms, eff) if abs(e) > lenth["me"]]

# %% Tables
rows = []
for i, t in enumerate(fit_terms):
    is_effect = t in eff_terms
    rows.append({
        "term": t, "effect": 2 * res["coef"][i] if is_effect else None, "coef": res["coef"][i],
        "se": res["se"][i], "t": res["t"][i], "p": res["p"][i],
    })
tables = [{
    "key": "effects", "title": "Effects and coefficients (coded units)",
    "columns": [
        {"key": "term", "label": "Term", "type": "string"}, {"key": "effect", "label": "Effect", "type": "number"},
        {"key": "coef", "label": "Coefficient", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
        {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
    ],
    "rows": rows,
}]
tables.append({
    "key": "anova", "title": "Analysis of variance (sequential)",
    "columns": [
        {"key": "source", "label": "Source", "type": "string"}, {"key": "df", "label": "df", "type": "integer"},
        {"key": "ss", "label": "SS", "type": "number"}, {"key": "ms", "label": "MS", "type": "number"},
        {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
    ],
    "rows": res["anova"],
})
tables.append({
    "key": "coding", "title": "Factor coding",
    "columns": [{"key": "name", "label": "Factor", "type": "string"}, {"key": "low", "label": "Low (−1)", "type": "string"},
                {"key": "high", "label": "High (+1)", "type": "string"}, {"key": "center", "label": "Center (0)", "type": "string"}],
    "rows": [{"name": c["name"], "low": cs.fmt_num(c["low"]) if c["kind"] == "numeric" else c["low"],
              "high": cs.fmt_num(c["high"]) if c["kind"] == "numeric" else c["high"],
              "center": cs.fmt_num(c["center"]) if c["kind"] == "numeric" else "—"} for c in coding],
})
if res["aliases"]:
    tables.append({"key": "aliases", "title": "Aliased terms (not estimable separately)",
                   "columns": [{"key": "alias", "label": "Alias", "type": "string"}], "rows": [{"alias": a} for a in res["aliases"]]})

# %% Charts
charts = []
order_abs = np.argsort(-np.abs(eff), kind="stable")
if df_resid > 0:
    pareto_vals = np.abs(np.asarray(res["effect_t"]))
    from scipy import stats as _st
    margin = float(_st.t.ppf(1 - alpha / 2, df_resid))
    controls = {"margin": margin, "smargin": None}
    label = "|t|"
else:
    pareto_vals = np.abs(eff)
    controls = {"margin": lenth["me"], "smargin": lenth["sme"]}
    label = "|Effect|"
charts.append(cs.chart(
    "pareto", "pareto-effects", "Pareto chart of effects",
    {"effect": cs.col("Term", [eff_terms[i] for i in order_abs], "categorical"),
     "value": cs.col(label, [float(pareto_vals[i]) for i in order_abs])},
    controls=controls,
))
m = len(eff)
if m >= 2:
    asc = np.argsort(np.abs(eff), kind="stable")
    charts.append(cs.chart(
        "half-normal", "half-normal-effects", "Half-normal plot of effects",
        {"effect": cs.col("Term", [eff_terms[i] for i in asc], "categorical"),
         "abs_effect": cs.col("|Effect|", [float(abs(eff[i])) for i in asc]),
         "quantile": cs.col("Half-normal quantile", qa.half_normal_quantiles(m).tolist()),
         "significant": cs.col("Significant", [eff_terms[i] in sig for i in asc], "boolean")},
    ))
me_factor, me_level, me_mean = [], [], []
for c, (nm, lo, hi) in zip(coding, res["means"]):
    me_factor += [nm, nm]
    me_level += [cs.fmt_num(c["low"]) if c["kind"] == "numeric" else str(c["low"]), cs.fmt_num(c["high"]) if c["kind"] == "numeric" else str(c["high"])]
    me_mean += [lo, hi]
charts.append(cs.chart(
    "main-effects", "main-effects", "Main effects (mean response at each level)",
    {"factor": cs.col("Factor", me_factor, "categorical"), "level": cs.col("Level", me_level, "categorical"),
     "mean": cs.col(f"Mean {y_name}", me_mean)},
))
two = [i for i in order_abs if " × " in eff_terms[i] and eff_terms[i].count(" × ") == 1]
if two:
    a_name, b_name = eff_terms[two[0]].split(" × ")
    keep = ~(np.all(coded[:, [j for j in range(len(FACTORS)) if numeric[j]]] == 0, axis=1)) if any(numeric) else np.ones(len(y), dtype=bool)
    def lab(j, v):
        c = coding[j]
        return (cs.fmt_num(c["low"]) if v < 0 else cs.fmt_num(c["high"])) if c["kind"] == "numeric" else (c["low"] if v < 0 else c["high"])
    ja, jb = FACTORS.index(a_name), FACTORS.index(b_name)
    charts.append(cs.chart(
        "interaction", "interaction", f"Interaction: {a_name} × {b_name}",
        {"y": cs.col(y_name, y[keep].tolist()),
         "x": cs.col(a_name, [lab(ja, v) for v in coded[keep, ja]], "categorical"),
         "trace": cs.col(b_name, [lab(jb, v) for v in coded[keep, jb]], "categorical")},
    ))
if df_resid > 0:
    charts.append(cs.chart(
        "residuals", "residual-panel", "Residual diagnostics",
        {"fitted": cs.col("Fitted values", np.asarray(res["fitted"]).tolist()),
         "residual": cs.col("Residuals", np.asarray(res["resid"]).tolist())},
    ))

# %% Result
n_eff = len(eff_terms)
values = {
    "n": res["n"], "n_center": res["n_center"], "k": len(FACTORS), "df_resid": df_resid,
    "terms": list(fit_terms), "coef": list(map(float, res["coef"])),
    "effect_terms": list(eff_terms), "effects": list(map(float, eff)), "effect_p": list(map(float, res["effect_p"])),
    "lenth_pse": lenth["pse"], "lenth_me": lenth["me"], "lenth_sme": lenth["sme"],
    "r2": res["r2"], "adj_r2": res["adj_r2"], "pred_r2": res["pred_r2"], "s": res["s"], "curvature_p": res["curvature_p"],
    "aliases": list(res["aliases"]), "significant": sig, "n_significant": len(sig), "n_effects": n_eff,
    "significant_text": ", ".join(sig),
}
if sig:
    summary = f"{len(sig)} of {n_eff} effects stand out ({', '.join(sig)})"
else:
    summary = f"No effect stands out among the {n_eff} estimated"
summary += " by Lenth's method." if df_resid == 0 else f" at α = {alpha:g}."
cs.publish({
    "title": "Analyze a two-level factorial experiment (effects, Lenth, ANOVA)",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": res["n"],
    "summary": summary,
    "statistics": [
        {"key": "n", "label": "Runs", "value": res["n"], "format": "integer"},
        {"key": "n_center", "label": "Center runs", "value": res["n_center"], "format": "integer"},
        {"key": "df_resid", "label": "Residual df", "value": df_resid, "format": "integer"},
    ] + ([{"key": "r2", "label": "R²", "value": res["r2"]}, {"key": "s", "label": "S", "value": res["s"]}] if df_resid > 0 else
         [{"key": "lenth_pse", "label": "Lenth PSE", "value": lenth["pse"]}, {"key": "lenth_me", "label": "Margin of error", "value": lenth["me"]}]),
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": ["Effects are differences between the high and low settings (2 × the coded coefficient)."]
    + (["No residual degrees of freedom: effects are judged with Lenth's pseudo standard error (ME individual, SME simultaneous)."] if df_resid == 0 else []),
    "values": values,
})
R

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

# Analyze a two-level factorial experiment (effects, Lenth, ANOVA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method doe.analyze 1.0.1 · spec 6522775f4b2584ee
# Dataset: q1_filtration (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_doe_analyze(): coding, aliasing and Lenth twin of codesplash.quality.analyze

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/q1_filtration.parquet", col_select = c("Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring")))
n_input <- nrow(df)
df[["Stirring"]] <- factor(df[["Stirring"]], levels = c("slow", "fast"))  # stored level order
df <- df[stats::complete.cases(df[c("Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring")]), , 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("Filtration rate", "Temperature", "Pressure", "Formaldehyde (%)", "Stirring"))  # infinite values stop the run (registry/errors.yaml)

# %% Coding (low = -1, high = +1, center runs = 0)
y_name <- "Filtration rate"
factors_ <- c("Temperature", "Pressure", "Formaldehyde (%)", "Stirring")
kinds_ <- c("numeric", "numeric", "numeric", "categorical")
block_col <- NULL
y <- as.numeric(df[[y_name]])
coding <- list(); coded <- NULL; numeric_ <- logical()
for (j in seq_along(factors_)) {
  f <- factors_[j]
  cf <- if (kinds_[j] %in% c("categorical", "boolean")) cs_doe_code_factor(as.character(df[[f]]), kinds_[j], levels(df[[f]]), f)
        else cs_doe_code_factor(as.numeric(df[[f]]), kinds_[j], NULL, f)
  coded <- cbind(coded, cf$coded)
  coding[[j]] <- cf$info
  numeric_ <- c(numeric_, kinds_[j] == "numeric")
}
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = y_name)  # a constant response has no effects to estimate
block <- if (!is.null(block_col)) as.character(df[[block_col]]) else NULL
alpha <- 0.05

# %% Model: effects in coded units; aliased terms dropped
# Classic idiom: lm(y ~ (A + B + C)^2, data = coded) — the twin fits lm() on the retained columns and
# drops aliased terms the same way as the Python twin.
res <- cs_doe_analyze(y, coded, factors_, numeric_, order = 2, block = block, alpha = alpha)
df_resid <- res$df_resid
ln <- res$lenth
eff <- res$effects
eff_terms <- res$effect_terms
sig <- if (df_resid > 0) eff_terms[res$effect_p < alpha] else eff_terms[abs(eff) > ln$me]

# %% Tables
tables <- list(list(
  key = "effects", title = "Effects and coefficients (coded units)",
  columns = list(list(key = "term", label = "Term", type = "string"), list(key = "effect", label = "Effect", type = "number"),
                 list(key = "coef", label = "Coefficient", type = "number"), list(key = "se", label = "SE", type = "number"),
                 list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue")),
  rows = lapply(seq_along(res$terms), function(i) list(
    term = res$terms[i], effect = if (res$terms[i] %in% eff_terms) 2 * res$coef[i] else NULL, coef = res$coef[i],
    se = res$se[i], t = res$t[i], p = res$p[i]))
))
tables[[2]] <- list(
  key = "anova", title = "Analysis of variance (sequential)",
  columns = list(list(key = "source", label = "Source", type = "string"), list(key = "df", label = "df", type = "integer"),
                 list(key = "ss", label = "SS", type = "number"), list(key = "ms", label = "MS", type = "number"),
                 list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue")),
  rows = res$anova)
tables[[3]] <- list(
  key = "coding", title = "Factor coding",
  columns = list(list(key = "name", label = "Factor", type = "string"), list(key = "low", label = "Low (−1)", type = "string"),
                 list(key = "high", label = "High (+1)", type = "string"), list(key = "center", label = "Center (0)", type = "string")),
  rows = lapply(coding, function(c) list(name = c$name,
    low = if (c$kind == "numeric") cs_fmt_num(c$low) else c$low, high = if (c$kind == "numeric") cs_fmt_num(c$high) else c$high,
    center = if (c$kind == "numeric") cs_fmt_num(c$center) else "—")))
if (length(res$aliases)) tables[[4]] <- list(
  key = "aliases", title = "Aliased terms (not estimable separately)",
  columns = list(list(key = "alias", label = "Alias", type = "string")), rows = lapply(res$aliases, function(a) list(alias = a)))

# %% Charts
charts <- list()
order_abs <- order(-abs(eff), method = "radix")
if (df_resid > 0) {
  pareto_vals <- abs(res$effect_t)
  controls <- list(margin = stats::qt(1 - alpha / 2, df_resid), smargin = NULL)
  plab <- "|t|"
} else {
  pareto_vals <- abs(eff)
  controls <- list(margin = ln$me, smargin = ln$sme)
  plab <- "|Effect|"
}
charts[[1]] <- cs_chart("pareto", "pareto-effects", "Pareto chart of effects",
                        list(effect = cs_col("Term", eff_terms[order_abs], "categorical"), value = cs_col(plab, pareto_vals[order_abs])),
                        controls = controls)
m <- length(eff)
if (m >= 2) {
  asc <- order(abs(eff), method = "radix")
  charts[[length(charts) + 1]] <- cs_chart(
    "half-normal", "half-normal-effects", "Half-normal plot of effects",
    list(effect = cs_col("Term", eff_terms[asc], "categorical"), abs_effect = cs_col("|Effect|", abs(eff[asc])),
         quantile = cs_col("Half-normal quantile", cs_doe_half_normal(m)),
         significant = cs_col("Significant", eff_terms[asc] %in% sig, "boolean")))
}
lvl <- function(c, v) if (c$kind == "numeric") cs_fmt_num(v) else as.character(v)
me_factor <- unlist(lapply(coding, function(c) c(c$name, c$name)))
me_level <- unlist(lapply(coding, function(c) c(lvl(c, c$low), lvl(c, c$high))))
me_mean <- unlist(lapply(res$means, function(m) c(m$low, m$high)))
charts[[length(charts) + 1]] <- cs_chart(
  "main-effects", "main-effects", "Main effects (mean response at each level)",
  list(factor = cs_col("Factor", me_factor, "categorical"), level = cs_col("Level", me_level, "categorical"),
       mean = cs_col(paste("Mean", y_name), me_mean)))
two <- order_abs[grepl(" × ", eff_terms[order_abs]) & lengths(regmatches(eff_terms[order_abs], gregexpr(" × ", eff_terms[order_abs]))) == 1]
if (length(two)) {
  ab <- strsplit(eff_terms[two[1]], " × ", fixed = TRUE)[[1]]
  num_idx <- which(numeric_)
  keep <- if (length(num_idx)) !apply(coded[, num_idx, drop = FALSE] == 0, 1, all) else rep(TRUE, length(y))
  lab <- function(j, v) { c <- coding[[j]]; if (c$kind == "numeric") ifelse(v < 0, cs_fmt_num(c$low), cs_fmt_num(c$high)) else ifelse(v < 0, c$low, c$high) }
  ja <- match(ab[1], factors_); jb <- match(ab[2], factors_)
  charts[[length(charts) + 1]] <- cs_chart(
    "interaction", "interaction", sprintf("Interaction: %s × %s", ab[1], ab[2]),
    list(y = cs_col(y_name, y[keep]), x = cs_col(ab[1], lab(ja, coded[keep, ja]), "categorical"),
         trace = cs_col(ab[2], lab(jb, coded[keep, jb]), "categorical")))
}
if (df_resid > 0) charts[[length(charts) + 1]] <- cs_chart(
  "residuals", "residual-panel", "Residual diagnostics",
  list(fitted = cs_col("Fitted values", res$fitted), residual = cs_col("Residuals", res$resid)))

# %% Result
n_eff <- length(eff_terms)
values <- list(
  n = res$n, n_center = res$n_center, k = length(factors_), df_resid = df_resid,
  terms = I(res$terms), coef = I(res$coef), effect_terms = I(eff_terms), effects = I(eff), effect_p = I(res$effect_p),
  lenth_pse = ln$pse, lenth_me = ln$me, lenth_sme = ln$sme,
  r2 = res$r2, adj_r2 = res$adj_r2, pred_r2 = res$pred_r2, s = res$s, curvature_p = res$curvature_p,
  aliases = I(res$aliases), significant = I(sig), n_significant = length(sig), n_effects = n_eff,
  significant_text = paste(sig, collapse = ", ")
)
summary <- if (length(sig)) sprintf("%d of %d effects stand out (%s)", length(sig), n_eff, paste(sig, collapse = ", ")) else
  sprintf("No effect stands out among the %d estimated", n_eff)
summary <- paste0(summary, if (df_resid == 0) " by Lenth's method." else sprintf(" at α = %s.", format(alpha)))
stats_list <- list(list(key = "n", label = "Runs", value = res$n, format = "integer"),
                   list(key = "n_center", label = "Center runs", value = res$n_center, format = "integer"),
                   list(key = "df_resid", label = "Residual df", value = df_resid, format = "integer"))
stats_list <- c(stats_list, if (df_resid > 0) list(list(key = "r2", label = "R²", value = res$r2), list(key = "s", label = "S", value = res$s))
                else list(list(key = "lenth_pse", label = "Lenth PSE", value = ln$pse), list(key = "lenth_me", label = "Margin of error", value = ln$me)))
cs_publish(list(
  method = "doe.analyze",
  methodVersion = "1.0.1",
  title = "Analyze a two-level factorial experiment (effects, Lenth, ANOVA)",
  engine = cs_engine_info("stats", "codesplashr"),
  n = res$n,
  summary = summary,
  statistics = stats_list,
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = c("Effects are differences between the high and low settings (2 × the coded coefficient).",
            if (df_resid == 0) "No residual degrees of freedom: effects are judged with Lenth's pseudo standard error (ME individual, SME simultaneous)."),
  values = values
))

Sources

  • Montgomery, D. C. (2017). Design and analysis of experiments (9th ed.). Wiley. Chapters 6–8.
  • Lenth, R. V. (1989). Quick and easy analysis of unreplicated factorials. Technometrics, 31, 469–473.

From the CodeSplash method registry · doe.analyze v1.0.1.