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

use numISO country year $ICVS I003 I002A USA $imputable $notimputable if !mi(victim9) & !mi(`notimputable') using paneldata.dta, clear

* drop transition countries in 1989-1992
drop if I002A<3 & legor_so==1 & country!="China"

/* In prior drafts, the code snippet below dropped for each country observations with lesser coverage to avoid unnecessary imputation -- the less complete observations are either almost identical for the observed values (e.g., Norway), or from a distinctly different time period anyway (transition countries)
* I don't do that anymore because (a) it knocks out USA 1989, and (b) below there is some imputation for multiple years of same country anyway
egen coverage=rownonmiss(*), strok
bys country: egen greatestcoverage=max(coverage)
drop if coverage<greatestcoverage // I manually checked that these have less or equal coverage on each individual variable, with strict inequality for at least one
drop coverage greatestcoverage
*/


*** frequency weights for estimation
bys numISO: gen freq=_N

*** log-transformation
foreach crime of global ICVS {
sum `crime' if `crime'!=0
recode `crime' (0 = `=r(min)') // otherwise, level-0s become missing values during log transformation -- this matters only for car theft in one country
replace `crime'=ln(`crime')
label var `crime' "ln(`crime')"
}

capture: stset, clear
xtset numISO year


** MULTIPLE IMPUTATION **
* Doesn't explicitly take into account panel structure (i.e., more than one observation from same country, highly serially correlated). But this is partially neutralized by serial correlation of other variables, and matters only for:
* slave, ms: N/A
* wb_: NZL 1992/2004
* unempl: Albania 1996/2000, Belarus 1997/2000
* teenshare: Botswana 1997/2000, CZE 1996/2000, Croatia 1997/2000, Lithuania 1997/2000/2005, Latvia 1996/2000, Russia 1996/2000, Slovenia 1997/2001, Uganda 1996/2000, ZAF 1996/2000/2004

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  numISO country year $ICVS I003 I002A USA $notimputable `complete'

mi impute chained (regress) `imputed' = $notimputable `complete' $ICVS i.I003 i.I002A  if country!="USA", add($imputations) rseed(2138) bootstrap

save MI_ICVS_dataset, replace
