*! version 1.1.3 08/03/95 program define nptr version 3.1 local varlist "req ex max(1)" local if "opt" local in "opt" local options "By(string) noDetail Ordinal Midrank Score(string)" parse "`*'" if "`score'"!="" { di in y "Score " in r "option is no longer supported. Use" /* */ in y " by " in r "instead." exit 198 } if "`by'"=="" { di in red "You must specify the grouping variable" exit 198 } _crcunab `by' local by "$S_1" quietly { /* Mark usable observations before sorting */ tempvar usable gen byte `usable' = 1 `if' `in' /* Is the grouping variable a string variable? */ tempvar byvar local string = 0 cap conf string var `by' if _rc { local byvar "`by'" } else { local string = 1 sort `by' gen long `byvar' = cond(`by'=="",.,1) replace `byvar' = `byvar'[_n-1] + (`by'!=`by'[_n-1]) /* */ in 2/l if `byvar'[_n-1]!=. } /* Update the usable marker. */ replace `usable' = . if `varlist'==. | `byvar'==. /* Create score. */ tempvar score if "`ordinal'"!="" { sort `usable' `byvar' gen `score'=sum(`byvar'!=`byvar'[_n-1]) if `usable'!=. } else if "`midrank'"!="" { egen `score' = rank(`byvar') if `usable'!=. } else gen `score' = `byvar' sort `byvar' `usable' by `byvar' :replace `score'=`score'[1] /* Generate the rank sums. */ tempvar ranksum obs tie egen `ranksum' = rank(`varlist') if `usable'!=. gen long `obs' = 1 if `ranksum'!=. sort `ranksum' by `ranksum': gen `tie' = cond(_n==_N,sum(`obs'),.) replace `tie' = sum(`tie'*(`tie'*`tie'-1)) local ties = `tie'[_N] sort `byvar' by `byvar': replace `ranksum'=cond(_n==_N,sum(`ranksum'),.) by `byvar': replace `obs'=cond(_n==_N,sum(`obs'),.) /* Display the rank sums for each group. */ noi di if "`detail'"=="" { replace `usable' = cond((`obs'!=. & `obs'!=0),1,.) sort `usable' `score' local scol = 11 - length("`by'") noi di in gr _col(`scol') "`by'" _col(16) "score" /* */ _col(28) "obs" _col(37) "sum of ranks" local i=1 while `i'<_N & `usable'[`i']!=.{ if `string' { local jby = rtrim(`by'[`i']) local scol = 11 - length("`jby'") noi di in ye _col(`scol') "`jby'" %10.1g `score'[`i'] %10.0g `obs'[`i'] " " %10.1g `ranksum'[`i'] } else noi di in ye %10.1g = `by'[`i'] %10.1g `score'[`i'] %10.0g `obs'[`i'] " " %10.1g `ranksum'[`i'] local i = `i'+1 } noi di } /* Calculate the test statistic and p-value. */ tempvar T L L2 gen `T'=sum(`ranksum'*`score') gen `L'=sum(`score'*`obs') gen `L2'=sum(`score'*`score'*`obs') replace `obs'=sum(`obs') local T = `T' in l local L = `L' in l local L2 = `L2' in l local N = `obs' in l local ET = (`N'+1)*`L'/2 local a=`ties'/(`N'*(`N'*`N'-1)) /* adj for ties */ local VT = (1-`a')*(`N'*`L2'-`L'*`L')*(`N'+1)/12 local z = (`T'-`ET')/sqrt(`VT') local pval = 2*( 1-normprob(abs(`z'))) } di in gr " z = " in ye %5.2f `z' in gr ", chi-squared(1) = " in ye %6.2f `z'^2 di in gr " P>|z| = " in ye %6.4f `pval' global S_1 = `N' global S_2 = `T' global S_3 = `z' global S_4 = `pval' end