sysuse auto, clear quietly summarize mpg generate himpg = mpg > r(mean) tab foreign himpg, chi2 levelsof rep78, missing local(levels) postfile chi2tests rep78level pvalue sig chi2 chi2macro using "chi2tests.dta", replace gen chi2 = . foreach level of local levels { *local chi2 quietly tabulate foreign himpg if rep78==`level', chi2 replace chi2 = r(p) < 0.05 if rep78==`level' & r(p) != . if (r(p) < 0.05 & r(p) !=. ) { local chi2 = r(p) < 0.05 } else if (r(p) > 0.05 & r(p) !=.){ local chi2 = 0 } else { local chi2 = . } *note (r(p)<0.1) (chi2) give incorrect results, which is the point * of including them here post chi2tests (`level') (r(p)) (r(p)<0.1) (chi2) (`chi2') } postclose chi2tests use "chi2tests.dta", clear generate rejectnull = pvalue < 0.05