Skip to content

Instantly share code, notes, and snippets.

@LTLA
Created November 24, 2022 06:43
Show Gist options
  • Save LTLA/52e7865aaef77f931683c6f7a3706d69 to your computer and use it in GitHub Desktop.
Save LTLA/52e7865aaef77f931683c6f7a3706d69 to your computer and use it in GitHub Desktop.
Three-factor chi-squared test of independence
# Demonstrate that this is chi-squared distributed
# with xyz - (x-1) - (y-1) - (z-1) -1 d.f.
stat <- numeric(1000)
for (i in seq_along(stat)) {
N <- 1000
x <- rmultinom(1, size=N, prob=rep(1/27, 27))
dim(x) <- c(3,3,3)
p1 <- vapply(1:3, function(i) sum(x[i,,]), 1) / N
p2 <- vapply(1:3, function(i) sum(x[,i,]), 1) / N
p3 <- vapply(1:3, function(i) sum(x[,,i]), 1) / N
e <- outer(outer(p1, p2), p3) * N
stat[i] <- sum((x - e)^2/e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment