## "Introduction to clustered data - discrete data"
#### do-file for lecture 11b of VHM 8120
<<dd_include: "c:\vhm812-data\header.txt">>

~~~~
<<dd_do:>>
version 18
set more off
cd "c:\vhm812-data"

capture log close
log using l11b-intro_cluster_discrete, replace

*Random effects binary data
*Pig respiratory disease data
use pig_adg.dta, clear
* generate dichotomous atrophic rhinits variable
egen ar_g1=cut(ar), at(0, 1.5, 99) icodes

* 2x2 table analysis
cc pn ar_g1

* ordinary logistic regression
logit pn i.ar_g1
logit pn i.ar_g1,or

* random effect logistic regression 
melogit pn ar_g1 || farm:
melogit pn i.ar_g1 || farm:, or

*ICC // approximation to real ICC by pi^2/3 = 3.29
estat icc

* PA logistic regression
xtgee pn ar_g1, fam(binomial) link(logit) i(farm) robust

* Random effects models for count data
* open the tb_real dataset
use tb_real, clear
* Poisson model with no random effects
glm reactors i.type i.sex i.age, exp(tar) link(log) fam(poisson)
estimates store pois
nbreg reactors i.type i.sex i.age, exp(tar) 

* negative binomial model no random effects
glm reactors i.type i.sex i.age, exp(tar) link(log) fam(nbin ml)
estimates store nb
* Pearson dispersion parameter still large (2.95)

* Poisson model with normal distributed random effects
mepoisson reactors i.type i.sex i.age, exp(tar) || farm_id:
mepoisson reactors i.type i.sex i.age, exp(tar) irr || farm_id:
**same with meglm
meglm reactors i.type i.sex i.age, exp(tar) || farm_id:, fam(poisson)
estimates store pois_norm

* Negative binomial with Normal random effects
meglm reactors i.type i.sex i.age, exp(tar) || farm_id:, fam(nbin)
estimates store nb_norm
* the overdispersion lnalpha is non signfincant which suggests that the
* overdispersion is due to clustering since this model is exactly 
* the same as the Poisson with random effects

estimates store pois_norm
estimates table pois nb pois_norm nb_norm, se(%4.3f) b(%4.3f) 
estimates stats pois nb pois_norm nb_norm

log close
<</dd_do>>
~~~~