Analysis of variance
Do several groups share one mean? Analysis of variance splits the total variation into the part between groups and the part within them, and compares the two. Every sum of squares here is an exact fraction.
One way
import { anova, show } from "@ratmath/stats";
const a = anova({ A: [23, 25, 21, 24], B: [28, 30, 27, 29], C: [22, 20, 24, 23] });
String(a); // "one-way analysis of variance: p = 0.000711 (certified, greater)"
a.statistic; // 541/30
a.table; // between groups: df 2, ss 541/6; within groups: df 9, ss 45/2; total: df 11, ss 338/3
a.means; // { A: 93/4, B: 57/2, C: 89/4 }
a.etaSquared; // 541/676: the share of the variation explained by the groups
With groups, group sizes , group means and grand mean , the total sum of squares splits exactly:
If all groups have the same mean (and normal errors with a common variance), has the distribution. Large values mean the group means are further apart than the noise within groups explains. is the effect size.
It is a regression
const g = ["A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"];
const y = [23, 25, 21, 24, 28, 30, 27, 29, 22, 20, 24, 23];
dummies(g); // { B: [0,0,0,0,1,1,1,1,0,0,0,0], C: [...] }: A is the reference
String(linearModel(dummies(g), y)); // "y = 93/4 + 21/4·B − 1·C (n = 12, R² = 541/676)"
linearModel(dummies(g), y).fTest(); // p = 0.000711, the same test
Code each group but one as a 0/1 indicator column and regress. The intercept is the reference group's mean, each coefficient the difference between a group's mean and the reference's, equals , and the regression's F test is the ANOVA F test. The test suite checks these identities exactly, along with the two-group case: the pooled t statistic squared is the ANOVA F.
Two factors
const fert = ["lo","lo","hi","hi","lo","lo","hi","hi","lo","lo","hi","hi"];
const water = ["dry","wet","dry","wet","dry","wet","dry","wet","dry","wet","dry","wet"];
const yld = [10, 14, 13, 19, 11, 15, 12, 20, 9, 13, 14, 18];
const both = linearModel({ ...dummies(fert, { name: "fert" }), ...dummies(water, { name: "water" }) }, yld);
String(both); // "y = 19/2 + 4·fert=hi + 5·water=wet (n = 12, R² = 123/134)"
const onlyWater = linearModel(dummies(water, { name: "water" }), yld);
compareModels(onlyWater, both); // F = 39.27, p = 0.000147: fertiliser matters, given water
With more than one factor the sums of squares no longer split in a single way unless the design is balanced, so the question has to be asked precisely: does a factor improve the model that already contains the others? That is the nested-model F test from the regression page. Adding a product of indicator columns tests an interaction the same way.
@ratmath/stats and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.