Hi,

I plan on using the xtewreg package so I have to use demeaned data. My actual data is an unbalanced panel. In order to make sure my estimates were correct I compared the results of the regress and xtreg packages. There is hardly any difference between the coefficients of regress and xtreg when I don't included a lagged covariate. However, I noticed discrepancies across results when I lagged a covariate. I have included a reproducible example below to illustrate my observations.

Questions:
  1. If the researcher plans on using a lagged covariate and needs to demean the data, is the process to lag by unit first then demean or demean first then lag by unit?
  2. Why are my coefficients different when I use l1.mvalue versus when I used a manually created lag variable l_mvalue with xtreg? I'm not sure which method is best or correct.
Code:
clear all
webuse grunfeld, clear
*******************************************
* using balanced panel

xtset company year

* demean the data
* 1st way
foreach var of varlist invest mvalue kstock {    
  bysort company : egen mean_`var'_comp = mean(`var')
    gen dm_`var' = `var' - mean_`var'_comp
    }

bysort company : generate dm_l_mvalue = l1.dm_mvalue

* 2nd way
bysort company : generate l_mvalue = l1.mvalue
bysort company : egen mean_l_mvalue_comp = mean(l_mvalue)
gen dm2_l_mvalue = l_mvalue - mean_l_mvalue_comp
    
* Fixed Effects (Company) without lags
regress dm_invest dm_mvalue
xtreg invest mvalue, fe

* Fixed Effects (Company) with lags
regress dm_invest dm_l_mvalue
regress dm_invest dm2_l_mvalue
xtreg invest l_mvalue, fe
xtreg invest l1.mvalue, fe

* Fixed Effects (Company) with lags
regress dm_invest dm_l_mvalue dm_kstock
regress dm_invest dm2_l_mvalue dm_kstock
xtreg invest l_mvalue kstock, fe
xtreg invest l1.mvalue kstock, fe

*******************************************
* using unbalanced panel

drop in 5
drop in 32
drop in 33
drop in 34
drop in 62
drop in 63
drop in 64
drop in 65
drop in 152
drop in 189
xtset company year

* Fixed Effects (Company) without lags
regress dm_invest dm_mvalue
xtreg invest mvalue, fe

* Fixed Effects (Company) with lags
regress dm_invest dm_l_mvalue
regress dm_invest dm2_l_mvalue
xtreg invest l_mvalue, fe
xtreg invest l1.mvalue, fe

* Fixed Effects (Company) with lags
regress dm_invest dm_l_mvalue dm_kstock
regress dm_invest dm2_l_mvalue dm_kstock
xtreg invest l_mvalue kstock, fe
xtreg invest l1.mvalue kstock, fe