Algorithm Search⌘K

Algorithmcore

Two-way analysis of variance

Also called two-way ANOVA, two-factor ANOVA.

Tests the main effects of two factors and their interaction by F ratios of nested residual sums of squares. Exact F laws under normal errors; unbalanced data need type I, II or III.

Time
Θ(n p^2) worst · best
Space
Θ(n p) extra
Where
n = the total number of observations; p = the number of cells, a times b
Properties
deterministicexactofflineiterative
Origin
Ronald A. Fisher, Frank Yates, 1925

Two-way analysis of variance tests the effects of two factors on a response, for example a fertilizer (factor A) and a crop variety (factor B), measured in every combination. It tests three null hypotheses: no effect of A, no effect of B, and no interaction, which means that the effect of A is the same at every level of B. Each test is a regression F-test: the drop in the residual sum of squares when the term is added to a smaller model, per degree of freedom, over the residual mean square of the full model. Under normal errors with a common variance each statistic has an exact F law. When every cell has the same number of observations, the sums of squares are orthogonal and the analysis has one answer. When the cells are unbalanced, the sum of squares of a term depends on which other terms are in the smaller model, and there are three standard choices, called type I, II and III. They test different hypotheses, so a report must say which one it used.

In plain words

You grow plants under two treatments at once, say fertilizer and watering, in every combination. You want to know whether fertilizer matters, whether watering matters, and whether the best fertilizer depends on the watering. Two-way ANOVA answers the three questions from one experiment, each by comparing the spread it explains with the noise between plants that got the same treatment pair. If every combination has the same number of plants, the three questions separate cleanly. If some combinations have more plants than others, the factors overlap. The part of the variation that fertilizer "explains" then depends on whether watering was taken into account first, and different programs report different numbers. Say which convention you used.

The problem

Model. Factor A has levels i=1,…,ai = 1, \dots, a and factor B has levels j=1,…,bj = 1, \dots, b. Cell (i,j)(i, j) holds nij≥1n_{ij} \ge 1 observations yijly_{ijl}, l=1,…,nijl = 1, \dots, n_{ij}, with n=∑nij>abn = \sum n_{ij} > ab. The model is

yijl=μij+eijl=m+αi+βj+γij+eijl,y_{ijl} = \mu_{ij} + e_{ijl} = m + \alpha_i + \beta_j + \gamma_{ij} + e_{ijl},

with iid N(0,σ2)N(0, \sigma^2) errors and the sum-to-zero constraints ∑iαi=∑jβj=0\sum_i\alpha_i = \sum_j\beta_j = 0 and ∑iγij=∑jγij=0\sum_i\gamma_{ij} = \sum_j\gamma_{ij} = 0. Then mm is the mean of the abab cell means, αi=μˉi⋅−m\alpha_i = \bar\mu_{i\cdot} - m is the deviation of the unweighted row mean of the cell means, βj\beta_j the same for columns, and γij\gamma_{ij} the interaction. The additive model sets every γij=0\gamma_{ij} = 0.

Hypotheses. HABH_{AB}: all γij=0\gamma_{ij} = 0 (no interaction); HAH_A: no A effect; HBH_B: no B effect. With an interaction, "no A effect" needs a definition, and the types define it differently (below).

Statistics. For column sets S⊂LS \subset L let RSS(S)RSS(S) be the residual sum of squares of the least squares fit of yy on the columns of SS. The columns are the intercept 11, the a−1a - 1 effect-coded columns of A (level i<ai < a gets +1+1, level aa gets −1-1), the b−1b - 1 columns of B, and the (a−1)(b−1)(a-1)(b-1) products AB. The term's sum of squares is SS=RSS(S)−RSS(L)SS = RSS(S) - RSS(L) on d=∣L∣−∣S∣d = |L| - |S| degrees of freedom, and

F=SS/dSSE/(n−ab),SSE=RSS({1,A,B,AB}).F = \frac{SS/d}{SSE/(n - ab)}, \qquad SSE = RSS(\{1, A, B, AB\}).
term type I (A first) type II type III
A RSS(1)−RSS(1,A)RSS(1) - RSS(1, A) RSS(1,B)−RSS(1,A,B)RSS(1, B) - RSS(1, A, B) RSS(1,B,AB)−SSERSS(1, B, AB) - SSE
B RSS(1,A)−RSS(1,A,B)RSS(1, A) - RSS(1, A, B) RSS(1,A)−RSS(1,A,B)RSS(1, A) - RSS(1, A, B) RSS(1,A,AB)−SSERSS(1, A, AB) - SSE
AB RSS(1,A,B)−SSERSS(1, A, B) - SSE same same

Type III with effect coding tests HA:μˉ1⋅=⋯=μˉa⋅H_A: \bar\mu_{1\cdot} = \dots = \bar\mu_{a\cdot}, equal unweighted marginal means of the cell means. Type II tests "no A effect" in the additive model; with an interaction its hypothesis is a weighted one whose weights depend on the cell counts. Type I is sequential and depends on the order of the factors.

Null distribution. Exact: each FF has the Fd,n−abF_{d, n-ab} law when the term's hypothesis holds, for every nn (Lemma 2 of the correctness proof). Under the alternative it is noncentral F.

Rejection rule, size and p-value. Reject when F≥F(d,n−ab,1−α)F \ge F_{(d, n-ab, 1-\alpha)}, with size exactly α\alpha for each test. The p-value is the upper tail P(Fd,n−ab>F)P(F_{d, n-ab} > F). The three tests together are not a family with error rate α\alpha.

Sensitivity. Each test reacts only to its own term. The interaction test reacts to non-parallel profiles of the cell means. When the interaction is large, the main effects average over effects of different sizes or signs, and the main effect tests can miss real effects or show effects that hold at no single level.

The algorithm

  1. TWO-WAY-ANOVA(y[1..n], A-labels, B-labels, type) ▷ every cell nonempty, n > a·b
  2. 1build the columns: 1, the effect columns of A and B, their products AB
  3. 2SSE ← RSS(1, A, B, AB) ▷ RSS by modified Gram-Schmidt, two passes
  4. 3if type = I: SS_A ← RSS(1) - RSS(1, A); SS_B ← RSS(1, A) - RSS(1, A, B)
  5. 4if type = II: SS_A ← RSS(1, B) - RSS(1, A, B); SS_B ← RSS(1, A) - RSS(1, A, B)
  6. 5if type = III: SS_A ← RSS(1, B, AB) - SSE; SS_B ← RSS(1, A, AB) - SSE
  7. 6SS_AB ← RSS(1, A, B) - SSE
  8. 7for each term: F ← (SS / d) / (SSE / (n - a·b)); p ← F̄(F; d, n - a·b)
  9. 8return the table of SS, d, F and p

RSS(S)RSS(S) orthogonalizes the columns of SS one by one with modified Gram-Schmidt, each twice, and removes the component of yy along each new unit vector; what is left is the residual. This is the QR decomposition without storing RR. The normal equations X⊤Xb=X⊤yX^\top X b = X^\top y are never formed. An empty cell makes the interaction columns linearly dependent, and the code raises an error. For balanced data the code also has the closed forms of the correctness proof.

Example

Balanced. A 2 x 3 layout with nij=2n_{ij} = 2:

B1B_1 B2B_2 B3B_3 row mean
A1A_1 12, 14 18, 16 21, 23 17.333
A2A_2 15, 13 24, 22 30, 28 22
column mean 13.5 20 25.5 19.667
source SS d F p
A 196/3=65.333196/3 = 65.333 1 32.667 0.00124
B 866/3=288.667866/3 = 288.667 2 72.167 0.0000636
AB 62/3=20.66762/3 = 20.667 2 5.1667 0.04957
error 12 6

The critical values are F(1,6,0.95)=5.9874F_{(1, 6, 0.95)} = 5.9874 and F(2,6,0.95)=5.1433F_{(2, 6, 0.95)} = 5.1433, so all three terms are significant at 5%, the interaction just. The cell means 13, 17, 22 in row 1 and 14, 23, 29 in row 2 show why: the A difference grows from 1 to 7 across the levels of B. Types I, II and III give the same table, in either order.

Unbalanced. A 2 x 2 layout with cells (1,1)={3,5}(1,1) = \{3, 5\}, (1,2)={7}(1,2) = \{7\}, (2,1)={6}(2,1) = \{6\} and (2,2)={10,12,11}(2,2) = \{10, 12, 11\}, cell means 4, 7, 6 and 11, and SSE=4SSE = 4 on 3 degrees of freedom:

test of SS F p
A, type I with A first 1083/28=38.6791083/28 = 38.679 29.01 0.0125
A, type II (= type I with B first) 676/51=13.255676/51 = 13.255 9.941 0.0511
A, type III 216/17=12.706216/17 = 12.706 9.529 0.0538
B, type I with A first (= type II) 1587/68=23.3381587/68 = 23.338 17.50 0.0249
B, type I with B first 1024/21=48.7621024/21 = 48.762 36.57 0.0091
B, type III 384/17=22.588384/17 = 22.588 16.94 0.0260
AB, every type 24/17=1.41224/17 = 1.412 1.059 0.3792

The test of A is significant at 5% by type I with A first and not by types II and III. Type I with A first credits A with the variation it shares with B, because the large cell (2,2)(2, 2) is at the high levels of both factors. The type III value is the squared marginal contrast: ψ^=12(4+7)−12(6+11)=−3\hat\psi = \frac12(4 + 7) - \frac12(6 + 11) = -3, with ∑c2/nij=14(12+1+1+13)=17/24\sum c^2/n_{ij} = \frac14(\frac12 + 1 + 1 + \frac13) = 17/24, and 9/(17/24)=216/179/(17/24) = 216/17. With treatment (0/1) coding instead of effect coding, the same "type III" comparison gives SSA=8/3SS_A = 8/3 and SSB=6SS_B = 6. On the balanced data above it gives SSA=1SS_A = 1 instead of 196/3196/3 and SSB=244/3SS_B = 244/3 instead of 866/3866/3. It tests the A difference at the reference level B1B_1 only, where the cell means are 13 and 14, and the B differences at A1A_1 only.

Correctness

Each sum of squares is RSS(S)−RSS(L)=∥(PL−PS)y∥2RSS(S) - RSS(L) = \|(P_L - P_S)y\|^2 for nested column spaces, where PP is an orthogonal projection, and SSE=∥(I−PF)y∥2SSE = \|(I - P_F)y\|^2 for the full model. The two projections have orthogonal ranges, so under normal errors the two squared lengths are independent chi-square variables, and the F ratio has an exact F law when (PL−PS)μ=0(P_L - P_S)\mu = 0. With effect coding this condition for type III A is equal unweighted marginal means. In a balanced layout the subspaces of A, B and AB are mutually orthogonal, because every inner product factors into a sum of a zero-sum vector. So each difference is the projection onto the term's own subspace, whatever the order, and all types agree. The proofs and the exact unbalanced computation are in the correctness proof below.

Proof: Two-way ANOVA sums of squares are differences of nested residual sums of squares with exact F laws, orthogonal in balanced layoutsfull

We prove that each sum of squares the code returns is the squared length of a projection, that each F statistic has an exact F law under the hypothesis that this projection of the mean is zero, that the three types coincide in balanced layouts, and that in unbalanced layouts they test different hypotheses. Factor A has levels i=1,…,ai = 1, \dots, a, factor B has levels j=1,…,bj = 1, \dots, b, and cell (i,j)(i, j) holds nij≥1n_{ij} \ge 1 observations, N=∑nijN = \sum n_{ij}. The model is yijl=μij+eijly_{ijl} = \mu_{ij} + e_{ijl} with iid N(0,σ2)N(0, \sigma^2) errors. For a set SS of columns, V(S)V(S) is their span in RN\mathbb R^N, PSP_S its orthogonal projection, and RSS(S)=∥(I−PS)y∥2RSS(S) = \|(I - P_S)y\|^2.

Lemma 1 (nested differences). If V(S)⊂V(L)V(S) \subset V(L), then RSS(S)−RSS(L)=∥(PL−PS)y∥2RSS(S) - RSS(L) = \|(P_L - P_S)y\|^2, and PL−PSP_L - P_S is the orthogonal projection onto V(L)⊖V(S)V(L) \ominus V(S), of rank dim⁡V(L)−dim⁡V(S)\dim V(L) - \dim V(S).

Proof. PLPS=PSPL=PSP_LP_S = P_SP_L = P_S because V(S)⊂V(L)V(S) \subset V(L). So PL−PSP_L - P_S is symmetric and idempotent. By Pythagoras, ∥(I−PS)y∥2=∥(I−PL)y∥2+∥(PL−PS)y∥2\|(I - P_S)y\|^2 = \|(I - P_L)y\|^2 + \|(P_L - P_S)y\|^2, since (I−PL)y(I - P_L)y and (PL−PS)y(P_L - P_S)y are orthogonal ((I−PL)(PL−PS)=0(I - P_L)(P_L - P_S) = 0). □\square

Lemma 2 (exact F law). Let FF denote the full model: the intercept, the a−1a - 1 effect columns of A, the b−1b - 1 of B and their (a−1)(b−1)(a-1)(b-1) products, with p=abp = ab columns. Every cell holds data, so these columns are linearly independent and V(F)V(F) is the set of vectors that are constant on each cell. For nested V(S)⊂V(L)⊂V(F)V(S) \subset V(L) \subset V(F) with d=dim⁡V(L)−dim⁡V(S)d = \dim V(L) - \dim V(S), the statistic

(RSS(S)−RSS(L))/dRSS(F)/(N−ab)\frac{(RSS(S) - RSS(L))/d}{RSS(F)/(N - ab)}

has the Fd,N−abF_{d, N - ab} law whenever (PL−PS)μ=0(P_L - P_S)\mu = 0, where μ\mu is the vector of cell means μij\mu_{ij}.

Proof. μ∈V(F)\mu \in V(F), so (I−PF)μ=0(I - P_F)\mu = 0. (PL−PS)(I−PF)=0(P_L - P_S)(I - P_F) = 0 because both PLP_L and PSP_S project into V(F)V(F). Lemma 2 of the one-way ANOVA proof (projections of a normal vector) gives independent χd2\chi^2_d and χN−ab2\chi^2_{N-ab} laws after division by σ2\sigma^2. □\square

The code (L3 to L6) computes exactly these differences: type I uses the chain {1}⊂{1,A}⊂{1,A,B}\{1\} \subset \{1, A\} \subset \{1, A, B\}, type II compares {1,B}\{1, B\} with {1,A,B}\{1, A, B\} for A and {1,A}\{1, A\} with {1,A,B}\{1, A, B\} for B, type III compares {1,B,AB}\{1, B, AB\} with the full model for A, and the interaction compares {1,A,B}\{1, A, B\} with the full model. The residual sums of squares come from modified Gram-Schmidt with reorthogonalization: the residual of yy after subtracting its components along an orthonormal basis of V(S)V(S) is (I−PS)y(I - P_S)y.

Lemma 3 (what type III tests). With the sum-to-zero (effect) coding, the type III hypothesis for A, (PF−P{1,B,AB})μ=0(P_F - P_{\{1,B,AB\}})\mu = 0, is μˉ1⋅=⋯=μˉa⋅\bar\mu_{1\cdot} = \dots = \bar\mu_{a\cdot}, where μˉi⋅=1b∑jμij\bar\mu_{i\cdot} = \frac1b\sum_j\mu_{ij} is the unweighted mean of the cell means of row ii.

Proof. Every vector of cell means can be written uniquely as μij=m+αi+βj+γij\mu_{ij} = m + \alpha_i + \beta_j + \gamma_{ij} with ∑iαi=0\sum_i\alpha_i = 0, ∑jβj=0\sum_j\beta_j = 0 and ∑iγij=∑jγij=0\sum_i\gamma_{ij} = \sum_j\gamma_{ij} = 0: take m=μˉ⋅⋅m = \bar\mu_{\cdot\cdot}, αi=μˉi⋅−μˉ⋅⋅\alpha_i = \bar\mu_{i\cdot} - \bar\mu_{\cdot\cdot}, βj=μˉ⋅j−μˉ⋅⋅\beta_j = \bar\mu_{\cdot j} - \bar\mu_{\cdot\cdot} and γij\gamma_{ij} the rest. The effect columns of A, B and AB span exactly the vectors of the forms αi\alpha_i, βj\beta_j and γij\gamma_{ij} with these constraints, by the coding. So the full model has μ\mu in it with unique coefficients, and μ∈V({1,B,AB})\mu \in V(\{1, B, AB\}) if and only if α=0\alpha = 0. Because V({1,B,AB})⊂V(F)V(\{1, B, AB\}) \subset V(F) and μ∈V(F)\mu \in V(F), (PF−P{1,B,AB})μ=0(P_F - P_{\{1,B,AB\}})\mu = 0 holds if and only if μ∈V({1,B,AB})\mu \in V(\{1, B, AB\}), that is if and only if every αi=μˉi⋅−μˉ⋅⋅\alpha_i = \bar\mu_{i\cdot} - \bar\mu_{\cdot\cdot} is 0. □\square

With treatment (0/1) coding the columns of B and AB span a different subspace, and the same comparison tests the A differences at the last level of B only. The test file shows that the two codings give different "type III" sums of squares on the same data. Type II for A, by contrast, is the same for every coding, because it depends only on the subspaces V({1,A,B})V(\{1, A, B\}) and V({1,B})V(\{1, B\}); its hypothesis is "no A effect" in the additive model, and in general it is a weighted hypothesis on the cell means whose weights depend on the nijn_{ij}.

Lemma 4 (balanced layouts are orthogonal). If nij=nn_{ij} = n for every cell, then RN\mathbb R^N is the orthogonal sum V0⊕VA⊕VB⊕VAB⊕VEV_0 \oplus V_A \oplus V_B \oplus V_{AB} \oplus V_E, where V0V_0 holds the constant vectors, VAV_A the vectors vijl=αiv_{ijl} = \alpha_i with ∑αi=0\sum\alpha_i = 0, VBV_B the vectors βj\beta_j with ∑βj=0\sum\beta_j = 0, VABV_{AB} the vectors γij\gamma_{ij} with zero row and column sums, and VEV_E the vectors with zero sum in every cell. So for every term the type I (in either order), type II and type III sums of squares are all equal to the squared length of the projection onto that term's own subspace:

SSA=bn∑i(yˉi⋅⋅−yˉ)2,SSB=an∑j(yˉ⋅j⋅−yˉ)2,SSAB=n∑i,j(yˉij⋅−yˉi⋅⋅−yˉ⋅j⋅+yˉ)2,SS_A = bn\sum_i(\bar y_{i\cdot\cdot} - \bar y)^2, \quad SS_B = an\sum_j(\bar y_{\cdot j\cdot} - \bar y)^2, \quad SS_{AB} = n\sum_{i,j}(\bar y_{ij\cdot} - \bar y_{i\cdot\cdot} - \bar y_{\cdot j\cdot} + \bar y)^2,

and SSE=∑(yijl−yˉij⋅)2SSE = \sum(y_{ijl} - \bar y_{ij\cdot})^2.

Proof. Inner products: ⟨α,β⟩=∑i,j,lαiβj=n∑iαi∑jβj=0\langle\alpha, \beta\rangle = \sum_{i,j,l}\alpha_i\beta_j = n\sum_i\alpha_i\sum_j\beta_j = 0. ⟨α,γ⟩=n∑iαi∑jγij=0\langle\alpha, \gamma\rangle = n\sum_i\alpha_i\sum_j\gamma_{ij} = 0, and ⟨β,γ⟩=0\langle\beta, \gamma\rangle = 0 the same way. The constant vector is orthogonal to VAV_A, VBV_B and VABV_{AB} because their entries sum to nn times a zero sum. Every vector of V0V_0, VAV_A, VBV_B and VABV_{AB} is constant on cells, and a vector of VEV_E sums to zero on each cell, so VEV_E is orthogonal to the other four. The dimensions 1+(a−1)+(b−1)+(a−1)(b−1)+(N−ab)1 + (a-1) + (b-1) + (a-1)(b-1) + (N - ab) add up to NN, so the sum is all of RN\mathbb R^N. The span of the effect columns of A is VAV_A, and similarly for B and AB. Every model in Lemma 2 is a sum of some of V0,VA,VB,VABV_0, V_A, V_B, V_{AB}, and for orthogonal subspaces PU⊕W=PU+PWP_{U \oplus W} = P_U + P_W. So each difference PL−PSP_L - P_S is the projection onto the one subspace that LL adds, whatever else is in the model. The closed forms are the projections: the projection onto VAV_A is yˉi⋅⋅−yˉ\bar y_{i\cdot\cdot} - \bar y at every unit of row ii, and so on. □\square

Lemma 5 (unbalanced layouts are not orthogonal). In general the types differ. In the 2 x 2 layout with cells (1,1)={3,5}(1,1) = \{3, 5\}, (1,2)={7}(1,2) = \{7\}, (2,1)={6}(2,1) = \{6\} and (2,2)={10,12,11}(2,2) = \{10, 12, 11\}:

  • type I with A first: SSA=1083/28SS_A = 1083/28, SSB∣A=1587/68SS_{B|A} = 1587/68;
  • type I with B first: SSB=1024/21SS_B = 1024/21, SSA∣B=676/51SS_{A|B} = 676/51;
  • type II: SSA=676/51SS_A = 676/51, SSB=1587/68SS_B = 1587/68;
  • type III: SSA=216/17SS_A = 216/17, SSB=384/17SS_B = 384/17;
  • the interaction: 24/1724/17 in every type, and SSE=4SSE = 4 on 3 degrees of freedom.

Proof. These are exact rational computations of the residual sums of squares of the nested models by the normal equations, done in the test file with fractions.Fraction; the code's floating point values agree to 10−910^{-9}. For type III, Lemma 3 gives a closed form to compare with. The row marginal contrast is ψ^=12(yˉ11+yˉ12)−12(yˉ21+yˉ22)=12(4+7)−12(6+11)=−3\hat\psi = \frac12(\bar y_{11} + \bar y_{12}) - \frac12(\bar y_{21} + \bar y_{22}) = \frac12(4 + 7) - \frac12(6 + 11) = -3, with variance σ2∑c2/n=σ2⋅14(12+1+1+13)=1724σ2\sigma^2\sum c^2/n = \sigma^2\cdot\frac14(\frac12 + 1 + 1 + \frac13) = \frac{17}{24}\sigma^2. The sum of squares of a one degree of freedom hypothesis is ψ^2/(∑c2/n)=9⋅24/17=216/17\hat\psi^2/(\sum c^2/n) = 9 \cdot 24/17 = 216/17, which matches. The A columns and the B columns are not orthogonal after the constant is removed, because the cell counts are not proportional, so the sum of squares of A depends on whether B is in the model. □\square

The order of the type I chain matters, but each chain still adds up: 1083/28+1587/68=1024/21+676/511083/28 + 1587/68 = 1024/21 + 676/51, since both equal RSS({1})−RSS({1,A,B})RSS(\{1\}) - RSS(\{1, A, B\}).

Termination. Each residual sum of squares orthogonalizes at most abab columns of length NN against each other, two passes each, and the code computes at most five of them. So it stops after O(N(ab)2)O(N(ab)^2) arithmetic operations. The F tails stop as in the one-way proof.

Theorem. For a two-way layout with every cell nonempty and N>abN > ab, the code returns for each term the difference of residual sums of squares of the two nested models named by the chosen type, and each F statistic has the exact Fd,N−abF_{d, N-ab} law under the normal model when the corresponding projection of the cell means is zero. In balanced layouts the three types coincide and equal the classical closed forms; in unbalanced layouts they test different hypotheses, and type III with effect coding tests equal unweighted marginal means.

Proof. Lemmas 1 to 5. ■\blacksquare

Complexity

On a real RAM, one RSS orthogonalizes at most p=abp = ab columns of length nn, each against all earlier ones, twice: O(np2)O(np^2) operations. The code computes at most five RSS values, so the time is Θ(np2)\Theta(np^2) and the extra space is Θ(np)\Theta(np) for the orthonormal basis. For balanced data the closed forms cost Θ(n)\Theta(n). A sparse or structured solver can do better for many levels, but pp is small in practice.

Numerical stability. Modified Gram-Schmidt with one reorthogonalization pass keeps the computed basis orthogonal to working precision, so the RSS values have small relative error even when the columns are nearly dependent (few observations in some cells). Solving the normal equations squares the condition number of the column matrix. The closed forms subtract means before squaring, as in one-way ANOVA. Differences of two RSS values can cancel when the term explains little; the result is then small in absolute terms, which is the right answer.

Properties

  • Exact. Each F test has size exactly α\alpha under the normal model with equal variances.
  • Balanced means orthogonal. With equal cell counts the sums of squares do not depend on the order or the type. With proportional counts, nij=ni⋅n⋅j/nn_{ij} = n_{i\cdot}n_{\cdot j}/n, the A and B columns are still orthogonal after the mean is removed, so types I and II agree in either order, but type III still differs.
  • Additive model. Without the AB term the error has n−a−b+1n - a - b + 1 degrees of freedom. With one observation per cell the interaction cannot be separated from the error, and the additive model is the randomized block design analysis.
  • Invariance of type II. Types I and II depend only on the column spaces, so any full-rank coding gives the same values. Type III depends on the coding of the interaction; with effect coding it tests equal unweighted marginal means.
  • Hierarchy. Type II respects marginality: it never tests a main effect after an interaction that contains it.

Variants and improvements

  • More factors. The same nested comparisons give k-way ANOVA. With two-level factors this is the factorial design analysis, where Yates's algorithm computes all effects at once.
  • Random and mixed effects. If the levels of B are a sample (subjects, batches), B and AB are random, and the F test of A uses the AB mean square as the denominator in the balanced case. The general tool is the linear mixed model fitted by restricted maximum likelihood.
  • Rank methods. The Friedman test handles the additive layout with one observation per cell without normality.
  • Multiple comparisons. Tukey's test on the marginal means of a balanced layout, with the error mean square of the full model.

When to use it

Use two-way ANOVA when two crossed factors are applied in every combination and the errors are close to normal with equal variances. Look at the interaction test and the profile plot of the cell means first. If the interaction is clear, interpret the effects of A within each level of B. In unbalanced data, prefer type II when there is no interaction, and type III with effect coding when you want equal-weight marginal means; never use type III with treatment coding.

Pitfalls

  • Not saying which type. In the unbalanced example, A has p = 0.0125, 0.0511 or 0.0538 depending on the type.
  • Type III with treatment coding. It silently tests a simple effect at the reference level, SSA=1SS_A = 1 instead of 65.33365.333 on the balanced data.
  • Main effects in the presence of interaction. A main effect averages over the levels of the other factor and can be zero while every simple effect is large.
  • One observation per cell with an interaction term. The full model then has no error degrees of freedom.
  • Empty cells. With an empty cell the interaction model is not of full rank, and the type III hypothesis is not defined.
  • Treating repeated measures as independent. Use a block or mixed model analysis instead.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

stdist.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
two_way_anova.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-way-anova/. The authors are listed in prov/E9ZZA5.jsonl.
"""Two-way analysis of variance with sequential (type I), type II and type III sums of squares.

Each sum of squares is a difference of residual sums of squares of two nested
least squares fits, RSS(smaller) - RSS(larger). The factors are coded by
sum-to-zero (effect) columns: level j < L of a factor with L levels gets the
indicator of j minus the indicator of level L. With this coding the type III
hypotheses are the equal marginal means of the cell means, as in the
textbooks; with treatment (0/1) coding the "type III" main effect would test
a simple effect at the last level of the other factor instead.

Residual sums of squares come from modified Gram-Schmidt with one
reorthogonalization pass, so no normal equations X^T X are formed.
For balanced data all three types agree with the classical closed forms in
balanced_two_way.
"""

import math
from collections.abc import Hashable, Sequence
from typing import NamedTuple

from stdist import f_sf


class Row(NamedTuple):
    source: str
    ss: float
    df: int
    f: float
    p: float


def effect_columns(labels: Sequence[Hashable], levels: Sequence[Hashable]) -> list[list[float]]:
    """Sum-to-zero coding: one column per level except the last."""
    last = levels[-1]
    return [[1.0 if v == lev else (-1.0 if v == last else 0.0) for v in labels]
            for lev in levels[:-1]]


def rss(columns: list[list[float]], y: Sequence[float]) -> float:
    """Residual sum of squares of the least squares fit of y on the columns (full column rank)."""
    basis: list[list[float]] = []
    r = list(y)
    for col in columns:
        v = list(col)
        for _ in range(2):  # modified Gram-Schmidt, then one reorthogonalization pass
            for q in basis:
                c = math.fsum(a * b for a, b in zip(q, v))
                v = [a - c * b for a, b in zip(v, q)]
        norm = math.sqrt(math.fsum(a * a for a in v))
        if norm <= 1e-10 * math.sqrt(math.fsum(a * a for a in col)):
            raise ValueError("the columns are linearly dependent (an empty cell?)")
        q = [a / norm for a in v]
        basis.append(q)
        for _ in range(2):
            c = math.fsum(a * b for a, b in zip(q, r))
            r = [a - c * b for a, b in zip(r, q)]
    return math.fsum(a * a for a in r)


def two_way_anova(y: Sequence[float], a: Sequence[Hashable], b: Sequence[Hashable],
                  ss_type: int = 2, interaction: bool = True) -> list[Row]:
    """ANOVA table rows for A, B, (A:B,) and Error. Every cell must hold data."""
    n = len(y)
    if not (len(a) == len(b) == n):
        raise ValueError("y, a and b must have the same length")
    la, lb = sorted(set(a), key=str), sorted(set(b), key=str)
    cells = {(u, v) for u, v in zip(a, b)}
    if interaction and len(cells) < len(la) * len(lb):
        raise ValueError("a cell is empty; the interaction model is not estimable")
    one = [[1.0] * n]  # @line L1
    ca = effect_columns(a, la)
    cb = effect_columns(b, lb)
    cab = [[x * z for x, z in zip(u, v)] for u in ca for v in cb] if interaction else []
    full = one + ca + cb + cab
    df_e = n - len(full)
    if df_e < 1:
        raise ValueError("no degrees of freedom are left for the error")
    sse = rss(full, y)  # @line L2
    if ss_type == 1:  # sequential: A, then B given A, then A:B given both
        r1, ra, rab = rss(one, y), rss(one + ca, y), rss(one + ca + cb, y)
        ss = {"A": r1 - ra, "B": ra - rab}  # @line L3
    elif ss_type == 2:  # each main effect after the other main effect
        rab = rss(one + ca + cb, y)
        ss = {"A": rss(one + cb, y) - rab, "B": rss(one + ca, y) - rab}  # @line L4
    elif ss_type == 3:  # each term after all others, sum-to-zero coding
        ss = {"A": rss(one + cb + cab, y) - sse, "B": rss(one + ca + cab, y) - sse}  # @line L5
        rab = rss(one + ca + cb, y)
    else:
        raise ValueError("ss_type must be 1, 2 or 3")
    df = {"A": len(ca), "B": len(cb)}
    if interaction:
        ss["A:B"] = rab - sse  # @line L6
        df["A:B"] = len(cab)
    mse = sse / df_e
    rows = []
    for name in ss:
        f = (ss[name] / df[name]) / mse  # @line L7
        rows.append(Row(name, ss[name], df[name], f, f_sf(f, df[name], df_e)))
    rows.append(Row("Error", sse, df_e, math.nan, math.nan))
    return rows  # @line L8


def balanced_two_way(cells: Sequence[Sequence[Sequence[float]]]) -> dict[str, float]:
    """Closed-form sums of squares of a balanced a x b layout, cells[i][j] holding n values."""
    na, nb, n = len(cells), len(cells[0]), len(cells[0][0])
    cm = [[math.fsum(c) / n for c in row] for row in cells]
    am = [math.fsum(row) / nb for row in cm]
    bm = [math.fsum(cm[i][j] for i in range(na)) / na for j in range(nb)]
    g = math.fsum(am) / na
    return {
        "A": nb * n * math.fsum((m - g) ** 2 for m in am),
        "B": na * n * math.fsum((m - g) ** 2 for m in bm),
        "A:B": n * math.fsum((cm[i][j] - am[i] - bm[j] + g) ** 2 for i in range(na) for j in range(nb)),
        "Error": math.fsum((v - cm[i][j]) ** 2 for i in range(na) for j in range(nb)
                           for v in cells[i][j]),
    }
test_two_way_anova.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-way-anova/. The authors are listed in prov/E9ZZA5.jsonl.

import math
import random
from fractions import Fraction

import pytest

from two_way_anova import balanced_two_way, two_way_anova

UNBALANCED = {("a1", "b1"): [3, 5], ("a1", "b2"): [7], ("a2", "b1"): [6], ("a2", "b2"): [10, 12, 11]}
BALANCED = [[[12, 14], [18, 16], [21, 23]], [[15, 13], [24, 22], [30, 28]]]


def flatten(cells: dict) -> tuple[list, list, list]:
    y, a, b = [], [], []
    for (u, v), vals in cells.items():
        for x in vals:
            y.append(x)
            a.append(u)
            b.append(v)
    return y, a, b


def rss_exact(cols: list[list[int]], y: list[int]) -> Fraction:
    """RSS by solving the normal equations X^T X beta = X^T y in exact arithmetic."""
    k = len(cols)
    m = [[sum(Fraction(p) * q for p, q in zip(cols[i], cols[j])) for j in range(k)]
         + [sum(Fraction(p) * v for p, v in zip(cols[i], y))] for i in range(k)]
    for c in range(k):
        piv = next(r for r in range(c, k) if m[r][c] != 0)
        m[c], m[piv] = m[piv], m[c]
        for r in range(k):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [x - f * z for x, z in zip(m[r], m[c])]
    beta = [m[i][k] / m[i][i] for i in range(k)]
    return sum((v - sum(beta[i] * cols[i][t] for i in range(k))) ** 2 for t, v in enumerate(y))


def brute_force(y: list[int], a: list, b: list) -> dict[int, dict[str, Fraction]]:
    """Types I, II and III as explicit comparisons of nested models, in exact arithmetic."""
    la, lb = sorted(set(a), key=str), sorted(set(b), key=str)
    one = [[1] * len(y)]
    ca = [[1 if v == l else (-1 if v == la[-1] else 0) for v in a] for l in la[:-1]]
    cb = [[1 if v == l else (-1 if v == lb[-1] else 0) for v in b] for l in lb[:-1]]
    cab = [[p * q for p, q in zip(u, v)] for u in ca for v in cb]
    r = lambda cols: rss_exact(cols, y)
    full, add = r(one + ca + cb + cab), r(one + ca + cb)
    inter = add - full
    return {
        1: {"A": r(one) - r(one + ca), "B": r(one + ca) - add, "A:B": inter},
        2: {"A": r(one + cb) - add, "B": r(one + ca) - add, "A:B": inter},
        3: {"A": r(one + cb + cab) - full, "B": r(one + ca + cab) - full, "A:B": inter},
        0: {"Error": full},
    }


def table(rows) -> dict[str, float]:
    return {row.source: row.ss for row in rows}


def test_unbalanced_example_exact() -> None:
    y, a, b = flatten(UNBALANCED)
    exact = brute_force(y, a, b)
    assert exact[1] == {"A": Fraction(1083, 28), "B": Fraction(1587, 68), "A:B": Fraction(24, 17)}
    assert exact[2]["A"] == Fraction(676, 51) and exact[2]["B"] == Fraction(1587, 68)
    assert exact[3] == {"A": Fraction(216, 17), "B": Fraction(384, 17), "A:B": Fraction(24, 17)}
    assert exact[0]["Error"] == 4
    for t in (1, 2, 3):
        got = table(two_way_anova(y, a, b, t))
        for name, value in exact[t].items():
            assert abs(got[name] - float(value)) < 1e-10
        assert abs(got["Error"] - 4.0) < 1e-10


def test_type_three_is_the_marginal_mean_contrast() -> None:
    # Type III SS of A tests (mu11 + mu12)/2 = (mu21 + mu22)/2: psi_hat^2 / sum(c^2 / n).
    y, a, b = flatten(UNBALANCED)
    mean = {key: Fraction(sum(v), len(v)) for key, v in UNBALANCED.items()}
    size = {key: len(v) for key, v in UNBALANCED.items()}
    for factor, sign in (("A", lambda u, v: 1 if u == "a1" else -1),
                         ("B", lambda u, v: 1 if v == "b1" else -1),
                         ("A:B", lambda u, v: 1 if (u == "a1") == (v == "b1") else -1)):
        c = {key: Fraction(sign(*key), 1 if factor == "A:B" else 2) for key in mean}
        psi = sum(c[key] * mean[key] for key in mean)
        ss = psi ** 2 / sum(c[key] ** 2 / size[key] for key in mean)
        assert ss == brute_force(y, a, b)[3][factor]


def test_random_unbalanced_layouts() -> None:
    rng = random.Random(5)
    for _ in range(25):
        la, lb = rng.randint(2, 3), rng.randint(2, 3)
        y, a, b = [], [], []
        for i in range(la):
            for j in range(lb):
                for _ in range(rng.randint(1, 3)):
                    y.append(rng.randint(-20, 20))
                    a.append(f"a{i}")
                    b.append(f"b{j}")
        if len(y) <= la * lb:
            y.append(1)
            a.append("a0")
            b.append("b0")
        exact = brute_force(y, a, b)
        for t in (1, 2, 3):
            got = table(two_way_anova(y, a, b, t))
            for name, value in exact[t].items():
                assert abs(got[name] - float(value)) <= 1e-9 * max(1.0, float(value))


def test_balanced_types_agree_with_closed_form() -> None:
    y, a, b = [], [], []
    for i, row in enumerate(BALANCED):
        for j, cell in enumerate(row):
            for v in cell:
                y.append(v)
                a.append(f"A{i + 1}")
                b.append(f"B{j + 1}")
    closed = balanced_two_way(BALANCED)
    assert abs(closed["A"] - 196 / 3) < 1e-12 and abs(closed["B"] - 866 / 3) < 1e-12
    assert abs(closed["A:B"] - 62 / 3) < 1e-12 and closed["Error"] == 12.0
    grand = sum(y) / len(y)
    assert abs(sum(closed.values()) - sum((v - grand) ** 2 for v in y)) < 1e-9
    for t in (1, 2, 3):
        got = table(two_way_anova(y, a, b, t))
        for name in closed:
            assert abs(got[name] - closed[name]) < 1e-9
    rows = {row.source: row for row in two_way_anova(y, a, b)}
    assert abs(rows["A:B"].f - 31 / 6) < 1e-12 and rows["A:B"].df == 2
    assert abs(rows["A:B"].p - 0.04957118207549574) < 1e-10


def test_sequential_order_matters_when_unbalanced() -> None:
    y, a, b = flatten(UNBALANCED)
    ab = table(two_way_anova(y, a, b, 1))
    ba = table(two_way_anova(y, b, a, 1))  # B entered first
    assert abs(ba["A"] - 1024 / 21) < 1e-10 and abs(ab["A"] - 1083 / 28) < 1e-10
    assert abs((ab["A"] + ab["B"]) - (ba["A"] + ba["B"])) < 1e-10  # the joint SS does not depend on order


def test_additive_model_size() -> None:
    # One observation per cell, no interaction: the F-test of A has size alpha under the null.
    rng = random.Random(6)
    reps, alpha, rej = 2000, 0.05, 0
    a = [f"t{i}" for i in range(4) for _ in range(5)]
    b = [f"k{j}" for _ in range(4) for j in range(5)]
    for _ in range(reps):
        y = [rng.gauss(0.0, 1.0) + 3.0 * j for _ in range(4) for j in range(5)]
        rej += two_way_anova(y, a, b, 1, interaction=False)[0].p <= alpha
    assert abs(rej / reps - alpha) < 4.0 * math.sqrt(alpha * (1 - alpha) / reps)


def test_errors() -> None:
    with pytest.raises(ValueError):
        two_way_anova([1.0, 2.0, 3.0], ["a", "a", "b"], ["x", "y", "x"])  # empty cell
    with pytest.raises(ValueError):
        two_way_anova([1.0, 2.0, 3.0, 4.0], ["a", "a", "b", "b"], ["x", "y", "x", "y"])  # no error df
    with pytest.raises(ValueError):
        two_way_anova([1.0] * 8, ["a", "b"] * 4, ["x"] * 4 + ["y"] * 4, ss_type=4)

History

Fisher developed the analysis of variance for crossed classifications in the agricultural experiments at Rothamsted in the 1920s, and described it in Statistical Methods for Research Workers (1925) and The Design of Experiments (1935). Yates (1934) treated tables with unequal numbers in the cells. He proposed the method of fitting constants, which corresponds to type II, and the method of weighted squares of means, which corresponds to type III. The names type I to type IV come from the SAS GLM procedure of the 1970s.

References

  1. Frank Yates, The analysis of multiple classifications with unequal numbers in the different classes, Journal of the American Statistical Association 29(185), 1934, pp. 51 to 66 (fitting constants and the weighted squares of means for unbalanced two-way data)
  2. Douglas C. Montgomery, Design and Analysis of Experiments, tenth edition, Wiley, 2019, Chapter 5 (introduction to factorial designs, the two-factor factorial design and its analysis of variance)
  3. George A. F. Seber and Alan J. Lee, Linear Regression Analysis, second edition, Wiley, 2003, Chapter 8 (analysis of variance, two-way classifications with equal and unequal numbers per cell; chapter-level locator)
  4. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Chapter 11 (analysis of variance and regression; chapter-level locator)
  5. Ronald A. Fisher, Statistical Methods for Research Workers, Oliver and Boyd, 1925, online text of the first edition, Chapter VIII (further applications of the analysis of variance)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example