Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Last active July 9, 2024 09:32
Show Gist options
  • Save abikoushi/02ad9881f156de026e0187719b873cb9 to your computer and use it in GitHub Desktop.
Save abikoushi/02ad9881f156de026e0187719b873cb9 to your computer and use it in GitHub Desktop.
Chi-square vs Fisher exact test
using Distributions
using Plots
function Chisqtest(tab, beta0)
beta = log(tab[2,2]) - log(tab[2,1]) - (log(tab[1,2])-log(tab[1,1]))
V = sum(inv.(tab))
return ccdf(Chisq(1.0), (beta-beta0)^2/V)
end
function Fishertest(X, phi)
cs = sum(X, dims=1)
rs = sum(X, dims=2)
f(x, phi) = pdf(FisherNoncentralHypergeometric(cs[1],cs[2],rs[1], exp(phi)), x)
prob = f.(0:cs[1], phi)
return sum(prob[prob .<= prob[X[1,1]+1]])
end
X = [12 6; 5 12]
pf(phi) = Fishertest(X, phi)
pc(phi) = Chisqtest(X, phi)
plot(x->pf(x), label="Fisher", -5, 5)
plot!(x->pc(x), label="Chisq")
png("pplot.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment