*
* @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]
*   [PRINT]/NOPRINT
*   TITLE =title for regression ["Pooled Mean Group"]
*
* Revision schedule:
*   10/2002 Written by Estima.
*   05/2012 Added TITLE and PRINT options. Modernized handling of SMPL.
*
procedure MeanGroup depvar start end
type series depvar
type integer start end
*
option equation 	*define
option series   	smpl
option switch   	print		1
option string   	title
*
local vect[int] 	reglist
local integer 		startl endl starti endi
local integer 		i
local integer 		nindiv ncoeff tmax tend regnobs
local real        pt nt
local symm 			xxgls
local vect 			betagls
local equation 	paneleqn
local series      icount u
local string      ltitle
*
enter(varying) reglist
*
inquire(regressorlist) startl<<start endl<<end
# depvar reglist
equation paneleqn depvar
# reglist
*
compute ncoeff=%eqnsize(paneleqn)
*
* Do a silent LINREG to get the SMPL for the data
*
linreg(noprint,smpl=smpl,equation=paneleqn) * start end u
compute startl=%regstart(),endl=%regend(),regnobs=%nobs
*
* Figure out the number of covered individuals and the number of data
* points for each.
*
compute starti=%indiv(startl),endi=%indiv(endl)
panel(icount=1.0,smpl=%valid(u),compress) u startl endl icount
set icount  starti endi = %if(%valid(icount),icount,0.0)
sstats(max) starti endi icount>>pt
sstats      starti endi (icount>0)>>nt
compute tmax=fix(pt),tend=%panelobs()
compute nindiv=fix(nt)
*
dim xxgls(ncoeff,ncoeff) betagls(ncoeff)
*
* Run OLS regressions over each individual. Sum the covariance matrices
* and coefficients.
*
compute xxgls  =%const(0.0)
compute betagls=%const(0.0)
do i=starti,endi
   if icount(i)==0
      next
   linreg(smpl=smpl,noprint,equation=paneleqn) * i//1 i//tend
   compute xxgls  =xxgls+%seesq*%xx
   compute betagls=betagls+%beta
end do i
*
* Scale to get the estimates
*
compute xxgls  =(1.0/nindiv^2)*xxgls
compute betagls=(1.0/nindiv)*betagls
*
if %defined(title)
   compute ltitle=title
else
   compute ltitle="Pooled Mean Group"
*
*
linreg(print=print,create,equation=paneleqn,smpl=%valid(u),define=define,$
  coeffs=betagls,covmat=xxgls,form=chisquared,title=ltitle) * startl endl
*
compute %ngroup=nindiv
*
end

