Type 3 Sum of Squares with StatsModels
For an easy primer on the differences between the types of sum of squares,
The code that is used in the examples is for R, however the explanation
in order to get the correct Type 3 sum of square calculations, one needs
to enter the formula a bit differently. It's not anything major, but something
that has to be known otherwise the results (without this step) are incorrect.
Let's get to it.
StatsModels ANOVA with Type 3 Sum of Squares
Will use a data set from Stata called systolic that is accessible a few ways.
One way is to load it via Stata's website it's self, however since this demonstration
is for StatsModels, this demonstration will use StatsModels' method.
Now to load the required libraries and the data.
import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols
stata = sm.datasets.webuse('systolic')
Now to run the ANOVA with Type 3 sum of squares using StatsModels.
model = ols('systolic ~ C(drug, Sum) + C(disease, Sum) + C(drug, Sum):C(disease, Sum)', data=stata).fit()
aov_table = sm.stats.anova_lm(model, typ=3)
|C(drug, Sum):C(disease, Sum)
That's all it takes! Now the sum of squares are being calculated as they should.