version 5.0
*!  19april1999; 5april2001
*!  program contributed by Frauke Kreuter
*!  calculate the random group variance estimator
*!  Wolter (1985) Introduction to Variance estimation. S.21
program define ranvar2
	syntax varlist(max=2 numeric) [iw] [if]
	tokenize "`varlist'"
	if `"`if'"' ~= "" {
		preserve
		quietly keep `if'
	}
	capture drop helpg
	egen helpg = group(`2')
*   tempvar helpg
*   sort `2' /*statt egen angeblich schnell, noch pruefen*/
*   quietly by `2': gen `helpg' =1 if _n==1  /*recode the grouping variable*/
*   replace `helpg' = sum(`helpg')
	quietly tab helpg	/*tabulates the grouping variable*/
	local max=r(r)		/*to keep the number of random groups*/
	preserve
	svyset, clear
	quietly svymean `1' [`weight' `exp']	/*summarize the dependent variable*/
	matrix n = e(N_pop)
	matrix x0 =  e(est)     	/*mean for the whole sample*/
	matrix rgv = 0		/*macro for random variance estimator */
	local i = 1
				/*loop for each random group*/
	while `i' <= `max' {
		  quietly svymean `1' [`weight' `exp'] if helpg == `i'
		  matrix xr = e(est)
		  matrix xdif = xr-x0
		  matrix rgv = rgv+(xdif*xdif')
		  local i = `i'+1
*		  matrix list rgv
	}
	local rgv1 = rgv[1,1]
	local rgst = sqrt((`rgv1'/`max'*(`max'-1)))
*	di `rgst'			/*dies anders als bei ranvar pruefen*/
*	di "`rgst'"
	local x0h  x0[1,1]
	local ku  `x0h' -1.96*`rgst'
	local ko  `x0h' +1.96*`rgst'
	di in green "Standard Error (random-group-conzept)"
	di
	di in green _col(1) "AV Variable:" _col(20) in y "`1'"
	di in green _col(1) "RG Variable:" _col(20) in y "`2'"
	di in green _col(1) "Number of obs =" _col(20) in y n[1,1]
	di in green _col(1) "Number of Groups: " _col(20) in y `max'
	di
	di in green _col(1) " mean " _col(15)"Std. Err." /*
			    */_col(30)"[95% Conf. Interval]"
        di in green _dup(13) "-" "+" _dup(14) "-" "+" _dup(20) "-"
	di in yellow _col(1) x0[1,1] _col(15) `rgst' /*
			    */_col(30) `ku'  in green " -- " in yellow `ko'
	drop helpg
end