In: Statistics and Probability
R code to obtain the goodness of fit G^2, its p-value, and its AIC value given a dataset?
1. In case of discrete data (for example Goodness-of-fit test for poisson distribution) :
library(vcd)
gf<-goodfit(x.poi,type= "poisson",method= "MinChisq")
summary(gf)
plot(gf,main="Count data vs Poisson distribution")
2. In case of continuous data (for example Goodness-of-fit test for gamma distribution) :
x.gam.cut<-cut(x.gam,breaks=c(0,3,6,9,12,18))
table(x.gam.cut)
## computing expected frequencies
(pgamma(3,shape=a.est,rate=l.est)-pgamma(0,shape=a.est,rate=l.est))*200
(pgamma(6,shape=a.est,rate=l.est)-pgamma(3,shape=a.est,rate=l.est))*200
(pgamma(9,shape=a.est,rate=l.est)-pgamma(6,shape=a.est,rate=l.est))*200
(pgamma(12,shape=a.est,rate=l.est)-pgamma(9,shape=a.est,rate=l.est))*200
(pgamma(18,shape=a.est,rate=l.est)-pgamma(12,shape=a.est,rate=l.est))*200
f.ex<-c(20,71,61,31,17) ## expected frequencies vector
f.os<-vector()
for(i in 1:5) f.os[i]<- table(x.gam.cut)[[i]] ## empirical frequencies
X2<-sum(((f.os-f.ex)^2)/f.ex) ## chi-square statistic
gdl<-5-2-1 ## degrees of freedom
1-pchisq(X2,gdl) ## p-value