*
* @MeanGroup( options )  depvar start end
* # list of regressors
*
* MeanGroup computes a mean group estimator for a panel data set. This does a
* simple weighted average of the coefficient vectors, with a compatible
* calculation for the covariance matrix. The procedure SWAMY.SRC does a GLS matrix
* weighted average.
*
* Parameters:
*   depvar      dependent variable
*   start end   range to estimate
*
* Note: This procedure uses start and end only to determine the range of
* individuals to use in the estimation. It will use all valid observations for
* each individual within that range. Use the SMPL option if you want to skip
* observations for reasons other than lack of data.
*
* Options:
*   define=equation to define [none]
*   smpl  =SMPL series [none]
*
* Revision schedule:
*   10/2002 Written by Estima.
*
procedure MeanGroup depvar start end
type series depvar
type integer start end
*
option equation *define
option series   smpl
*
local vect[integer] reglist
local integer startl endl
local integer i
local integer nindiv ncoeff ntime firsti lasti
local vect[symm] xxmats
local vect[vect] betas
local vector sigmas
local symm xxgls
local vect betagls
local equation paneleqn
*
enter(varying) reglist
*
inquire(regressorlist) startl<<start endl<<end
# depvar reglist
equation paneleqn depvar
# reglist
*
compute ncoeff=%eqnsize(paneleqn)
compute firsti=%indiv(startl),lasti=%indiv(endl)
compute nindiv=%indiv(endl)-%indiv(startl)+1
compute ntime =2//1-1//1
dim xxmats(nindiv) betas(nindiv) sigmas(nindiv)
dim xxgls(ncoeff,ncoeff) betagls(ncoeff)
*
* First pass, run OLS regressions over each individual. Save %xx, %beta and %seesq.
*
do i=1,nindiv
   linreg(smpl=smpl,noprint,equation=paneleqn) * (firsti+i-1)//1 (firsti+i-1)//ntime
   compute xxmats(i)=%xx
   compute betas(i)=%beta
   compute sigmas(i)=%seesq
end do i
*
* Second pass. Compute the mean group covariance matrix.
*
compute xxgls=%const(0.0)
do i=1,nindiv
   compute xxgls=xxgls+sigmas(i)*xxmats(i)
end do i
compute xxgls=(1.0/nindiv**2)*xxgls
*
* Final pass. Compute the grand coefficient matrix
*
compute betagls=%const(0.0)
do i=1,nindiv
   compute betagls=betagls+(1.0/nindiv)*betas(i)
end do i
linreg(create,equation=paneleqn,define=define,coeffs=betagls,covmat=xxgls,noscale) *
end

