I am extremely confused about getting the between group variance component from an ANOVA. To my understanding, variance within groups ($V_w$) equals the mean of squares within groups ($MSW$) and the variance between groups ($V_b$) can be calculated from the mean of squares between groups ($MSB$) as following $MSB = MSW + k*V_b$, where $k$ is the number of observations per level of the grouping variable.
However, trying to follow this logic by hand or in R I am not able to get the variances right. Let's consider the following example with a subset of mtcars
with $k=4$.
m4 = mtcars %>% dplyr::filter(cyl == 4) %>% head(n=4)
m6 = mtcars %>% dplyr::filter(cyl == 6) %>% head(n=4)
m8 = mtcars %>% dplyr::filter(cyl == 8) %>% head(n=4)
df = dplyr::bind_rows(m4, m6, m8)
In the dataframe above, the total variance of mpg (var(df$mpg)
) is $21.95$.
If I use ANOVA now, the variances I calculate are:
aov(data = df, mpg ~ factor(cyl)) %>% summary()
# Df Sum Sq Mean Sq F value Pr(>F)
# factor(cyl) 2 160.86 80.43 8.984 0.00717 **
# Residuals 9 80.57 8.95
# ---
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
$V_w = 8.95$, and $V_b = (80.43-8.95)/4 = 17.87$, consequently, the total variance estimate is $Vw + Vb = 26.82$. But this value is larger than the one above. Why the difference? am I getting something wrong?
Also a couple of questions in case anybody knows. If I had different number of observations per level (e.g. as in the original mtcars data set, what would be the "$k$" parameter multiplying $V_b$ in $MSB$ ? Would it be possible to estimate $V_b$ in a similar way for a non-parametric design using Kruskal-Wallis?
Thanks