version 5.0
*!  19april1999; 5april2001
*!  program contributed by Frauke Kreuter
*!  calculate the random group variance estimator
*!  Wolter (1985) Introduction to VariancÉe estimation. S.21
program define ranvar
	syntax varlist(max=2 numeric) [aw] [if]
	tokenize "`varlist'"
	if `"`if'"' ~= "" {
		preserve
		quietly keep `if'
	}
	capture drop helpg
	egen helpg = group(`2')
*	sort `2'
*	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*/
	quietly sum `1' [`weight' `exp'] /*summarize the dependent variable*/
	local n = r(N)
	local x0 = r(mean)	/*mean for the whole sample*/
	local rgv = 0		/*macro for random variance estimator */
	local i = 1
				/*loop for each random group*/
	while `i' <= `max' {
		  quietly sum `1' [`weight' `exp'] if helpg == `i'
		  local xr = r(mean)
		  local rgv = `rgv'+(`xr'-`x0')^2
		  local i = `i'+1
*		  di `rgv'
	}
	local rgst = sqrt(`rgv'/(`max'*(`max'-1)))
*	di `rgst'
*	di "`rgst'"
	local ku = `x0'-1.96*(`rgst')
	local ko = `x0'+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'
	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' _col(15)`rgst' /*
			    */_col(30) `ku'  in green " -- " in yellow `ko'
	drop helpg
end