local notimputable: subinstr global notimputable " " ", ", all

*** A. deaths
use numISO country year USA ln_IHMEdrugdeaths $imputable $notimputable if !mi(ln_IHMEdrugdeaths) & year==2005 & !mi(`notimputable') using paneldata.dta, clear
drop year
xtset, clear
capture: stset, clear

local imputed ""
local complete ""
foreach var of varlist $imputable {
	quietly misstable sum `var'
	if r(N_eq_dot)!=. local imputed "`imputed' `var'"
	else local complete "`complete' `var'"
	}

mi set wide
mi register imputed `imputed'
mi register regular ln_IHMEdrugdeaths USA $notimputable `complete'
mi impute chained (regress) `imputed' = ln_IHMEdrugdeaths $notimputable `complete' if USA==0, add($imputations) rseed(2138) bootstrap
save MI_drugdeaths_dataset, replace

*** B. WDR
use ISO numISO country year USA $drugs $imputable $notimputable if year>1999 using paneldata.dta, clear

* log-transformation & moving 2011 values to 2010 (Mexico & Venezuela)
sort numISO year
foreach drug of global drugs {
replace `drug'=F.`drug' if year==2010 & mi(`drug') & !mi(F.`drug')
replace `drug'=ln(`drug')
label var `drug' "ln(`drug')"
}

* clean up
drop if year>2010
tempvar hasdata
egen `hasdata'=rownonmiss($drugs)
drop if `hasdata'==0
drop if mi(`notimputable') // don't drop earlier because it would knock out Mexico and Venezuela 2011; fewer countries affected here because N smaller to begin

xtset numISO year
capture: stset, clear

local imputed ""
local complete ""
foreach var of varlist $imputable {
	quietly misstable sum `var'
	if r(N_eq_dot)!=. local imputed "`imputed' `var'"
	else local complete "`complete' `var'"
	}

mi set wide
mi register imputed `imputed'
mi register regular USA $drugs $notimputable `complete' year

* actual imputations
foreach drug in $drugs {
mi impute chained (regress) `imputed' = `drug' $notimputable `complete' year if USA==0 & mi(`drug')==0, add($imputations) rseed(2138) bootstrap
}
capture drop __* // for some reason, __00000 was left in the data before
save MI_drugsWDR_dataset, replace
