*********************************************
*AnalyzeWACountiesVBM.do
**
*Analyze the treatment effect of Washington counties who
*switched to all-mail elections.
**
*Alan Gerber, Gregory Huber, Seth Hill, "Identifying the Effects of Elections Held All-Mail on
*Turnout: Staggered Reform in the Evergreen State."
*********************************************

clear
set more off

**************************
*County level voting age population.
*1990-1999: http://www.census.gov/popest/datasets.html#cntyinter
*2000-2009: http://www.census.gov/popest/counties/asrh/CC-EST2009-agesex.html.
**************************
*1996 pops.
infix year 1-2 stfips 5-6 county 7-9 age 11-12 racesex 14-14 hispanic 16-16 count 18-24 using "CensusCountyPopEstimates\STCH-icen1996.txt", clear
save "tmp_vap1996.dta", replace
infix year 1-2 stfips 5-6 county 7-9 age 11-12 racesex 14-14 hispanic 16-16 count 18-24 using "CensusCountyPopEstimates\STCH-icen1998.txt", clear
append using tmp_vap1996.dta
rm "tmp_vap1996.dta"

*Washington state and age >= 20 (bad age categories!) .
  *NOTE: Due to collapsed aged categories in 1996 and 1998, VAP count excludes 18 and 19
  *year olds in these years. Year fixed effects should reflect this fact.
keep if stfips == 53 & age >= 5
*Aggregate to the year-county.
keep year county count
collapse (sum) count, by(year county)
replace year = year + 1900
rename count vap
save "tmp_vap9698.dta", replace

*2000-2009 pops.
insheet using "CensusCountyPopEstimates\cc-est2009-agesex-53.csv", comma clear
drop if year < 3
recode year (3 = 2000) (4 = 2001) (5 = 2002) (6 = 2003) (7 = 2004) (8 = 2005) (9 = 2006) (10 = 2007) (11 = 2008) (12 = 2009)
tab year
gen vap = age18plus_tot
*Append in 1996 and 1998 vap created above.
append using "tmp_vap9698.dta"
rm "tmp_vap9698.dta"
*Propogate county name by county fips number.
sort county year
bysort county: replace ctyname = ctyname[_N] if ctyname == ""

label variable vap "Total Population Aged 18+"
keep year ctyname vap
gen county = subinstr(ctyname," County","",1)
keep year county vap
*Impute a 2010 observation, as estimates for 2010 are not yet available.
gen expander = (year == 2009) + 1
expand expander
drop expander
bys county year: replace year = 2010 if year[_n] == 2009 & year[_n-1] == 2009
*2010 pop = 2009 pop + same pct change in pop 2008 to 2009.
sort county year
by county: replace vap = vap[_n-1]*(1 + (vap[_n-1] - vap[_n-2])/vap[_n-2]) if year == 2010
save "CensusCountyPopEstimates\Washington.dta", replace

*County percent rural. Downloaded from Census.
insheet using "CensusCountyPopEstimates\DEC_00_SF1_P002.csv", comma clear
gen pctrural2000 = rural/total
label variable pctrural2000 "Percent county population rural, Census 2000"
rename geography county
replace county = subinstr(county," County","",1)
keep if state == "Washington"
keep county pctrural2000
save "CensusCountyPopEstimates\WashingtonRural2000.dta", replace

**************************
*County level election statistics.
*From http://www.sos.wa.gov/elections/absentee_stats.aspx.
**************************
insheet using "WA-County-VotesCast.csv", comma clear
label variable vbmonly "Election held all-mail"
sort county year
joinby county year using "CensusCountyPopEstimates\Washington.dta", unmatched(both)
tab _merge
drop _merge
joinby county using "CensusCountyPopEstimates\WashingtonRural2000.dta", unmatched(master)
tab _merge
drop _merge
*Create mean-deviated version of pctrural2000.
qui summ pctrural2000
qui gen pctrural_md = pctrural2000 - `r(mean)'
label variable pctrural_md "Percent county population rural, Census 2000 (mean-deviated)"

**************************
*Identify year of VBM switch.
*Note: There are a few discrepancies between these years and those documented on 
*the pdf at http://wei.secstate.wa.gov/osos/en/ElectionStatistics/VBM/Documents/
*2000-2010%20WA%20history%20of%20move%20to%20vbm.pdf. My readng of the turnout 
*numbers indicate this is accurate. Any inaccuracies surround 2005 versus 2006,
*so should not much affect things.
**************************
sort county year
by county: gen newlyvbm = (vbmonly[_n] != vbmonly[_n-1] & _n != 1)
label variable newlyvbm "First year under vote by mail"
di "Year of VBM Switch By County:"
cl county year if newlyvbm
gen newlyvbmXyear = newlyvbm*year
bys county: egen yearofswitch = max(newlyvbmXyear)
label variable yearofswitch "Year county switched to vote by mail"
*Ferry county was vote by mail since 1990s, Pierce not yet vote by mail in 2010.
replace yearofswitch = . if county == "Pierce" | county == "Ferry"
drop newlyvbmXyear

*Note the average ratio of registrants to vap in year prior to switch.
qui gen tmp = registered/vap
sort county year
*Replace all to missing except the ratio in the year prior to the switch.
qui bys county: replace tmp = . if newlyvbm[_n+1] != 1
qui summ tmp
di "Average ratio of registrants to vap in year prior to swtich: " string(`r(mean)',"%9.2f") "."
file open myfile using "RatioOfRegistrantsToVapInYearPriorToSwitch.txt", write replace
file write myfile "`r(mean)'"
file close myfile
qui drop tmp

*Calculate turnout as a proportion of voting age population.
gen turnoutofvap = cast / vap
label variable turnoutofvap "Turnout As Proportion of Voting Age Population"
label variable turnoutpct "Turnout As Proportion of Registered Voters"

*Calculate absentee rate as a proportion of voting age population.
gen absenteeofvap = absenteecast / vap
label variable absenteeofvap "Absentee Vote Rate As Proportion of Voting Age Population"
label variable absenteepct "Absentee Vote Rate As Proportion of Votes Cast"

*Calculate registration rate as a proportion of voting age population.
gen registeredofvap = registered / vap
label variable registeredofvap "Registration Count As a Proportion of Voting Age Population"
sort year registeredofvap
di "Registration rates in 2010:"
cl county year registeredofvap if year == 2010

*Measure change in number registered as a percentage of previous registrants.
sort county year
by county: gen changeregisteredpct = (registered[_n] - registered[_n-1])/registered[_n-1]
label variable changeregisteredpct "Percent Change in Number Registered From Previous Election"

*Nonstring version of county.
encode county, gen(county2)

*Election types.
gen electype = "Midterm"
replace electype = "OddYear" if mod(year,2) != 0
replace electype = "Presidential" if mod(year,4) == 0

*Create lagged turnout.
sort county electype year
by county electype: gen laggedturnoutpct = turnoutpct[_n-1]
label variable laggedturnoutpct "Turnout in Previous Election in Same Election Type"
by county electype: gen laggedturnoutofvap = turnoutofvap[_n-1]
label variable laggedturnoutofvap "Turnout in Previous Election in Same Election Type"
by county electype: gen laggedabsentee = absenteepct[_n-1]
label variable laggedabsentee "Absentee Rate in Previous Election in Same Election Type"

*Open a log to replace it.
qui log using "terciletests.log", text replace
qui log close

**************************
*Difference of means: counties already vbm in 2005 versus those switching after 2005.
*Compare mean turnout in 2002/2004 to mean turnout in 2008/2010.
*Alternatively, compare mean turnout in 2004 to mean turnout in 2008.
**************************
preserve
keep year county vbmonly turnoutpct
*Toggle here which elections to compare.
if (0) {
  *Average of midterm and presidential, before and after.
  keep if year == 2002 | year == 2004 | year == 2008 | year == 2010
  label define yeargroup 1 "2002/2004" 2 "2008/2010"
}
else {
  *Presidential turnout, before and after.
  keep if year == 2004 | year == 2008
  label define yeargroup 1 "2004" 2 "2008"
}
recode year (2002/2004=1) (2008/2010=2), gen(yeargroup)
label values yeargroup yeargroup
tab year yeargroup
*Coefficient and p-value on vbmonly from diff-in-diff regression.
gen i_secondyeargroup = (yeargroup == 2)
reg turnoutpct vbmonly i_secondyeargroup
qui test vbmonly
local se = _se[vbmonly]
local coef = _b[vbmonly]
sort county year
collapse (mean) turnoutpct vbmonly, by(county yeargroup)
*Drop cases where switch occurred in either period.
gen dropme = vbmonly == .5
bys county: egen dropme2 = max(dropme)
drop if dropme2 == 1
drop dropme*
*Identify treated counties that moved from one regime to the other between
*each election grouping.
egen switchedregime = sd(vbmonly[_n]), by(county)
replace switchedregime = (switchedregime != 0)
sort county
qui log using "switchedregimes.log", text replace
bys switchedregime: cl county if yeargroup == 1
qui log close

*Calculate mean and sd of turnout in switching and control counties,
*before and after intervention in 2005.
file open myfile using "Table02_MeanTurnoutBySwitch.csv", write replace
file write myfile "Election Years,Control Counties,Switched Counties" _n
forvalues i = 1/2 {
  local row : label(yeargroup) `i', strict
  local row2 = "           "
  *Control cases.
  qui summ turnoutpct if yeargroup == `i' & switchedregime == 0
  local row  = "`row'," + string(`r(mean)',"%9.2f")
  local row2 = "`row2',[" + string(`r(sd)',"%9.2f") + "]"
  *Switched cases.
  qui summ turnoutpct if yeargroup == `i' & switchedregime == 1
  local row  = "`row'," + string(`r(mean)',"%9.2f")
  local row2 = "`row2',[" + string(`r(sd)',"%9.2f") + "]"
  di "`row'" _n "`row2'"
  file write myfile "`row'" _n
  file write myfile "`row2'" _n
}
qui count if switchedregime == 0 & yeargroup == 1
file write myfile "N,`r(N)',"
qui count if switchedregime == 1 & yeargroup == 1
file write myfile "`r(N)'" _n
file write myfile "\hline" _n
*Write out coefficient and p-value from diff-in-diff regression above.
local outstring = "\multicolumn{3}{p{\textwidth}}{Coefficient and standard error on all-mail in differences-in-differences regression: " + string(`coef',"%9.3f") + " (" + string(`se',"%9.3f") + ").}"
file write myfile "`outstring'" _n
*file write myfile "Cell entries are average turnout in row's election years and column group." _n
*file write myfile "Standard deviations in brackets." _n
file close myfile

restore

**************************
*Difference of means for counties in individual-level analysis.
**************************
preserve
keep year county turnoutpct
*2006-2008 comparison counties.
keep if (county == "Island" & (year == 2006 | year == 2008)) | (county == "Klickitat" & (year == 2006 | year == 2008)) | (county == "King" & (year == 2006 | year == 2008)) | (county == "Pierce" & (year == 2006 | year == 2008)) | (county == "King" & (year == 2008 | year == 2010)) | (county == "Pierce" & (year == 2008 | year == 2010))

*2006-2008 comparison.
gen treated = .
replace treated = 1 if county == "Island" | county == "Klickitat"
replace treated = 0 if (county == "King" | county == "Pierce") & year < 2010

file open myfile using "MeanTurnoutBySwitch-IndividualModelCounties.csv", write replace
file write myfile "Comparing 2006 and 2008" _n
file write myfile "Election Year,Control Counties,Switched Counties" _n
foreach i in 2006 2008 {
  local row `i'
  *Control cases.
  qui summ turnoutpct if year == `i' & treated == 0
  local row  = "`row'," + string(`r(mean)',"%9.2f")
  *Switched cases.
  qui summ turnoutpct if year == `i' & treated == 1
  local row  = "`row'," + string(`r(mean)',"%9.2f")
  di "`row'"
  file write myfile "`row'" _n
}
qui count if treated == 0 & year == 2006
file write myfile "N,`r(N)',"
qui count if treated == 1 & year == 2006
file write myfile "`r(N)'" _n

*2008-2010 comparison.
replace treated = .
replace treated = 1 if county == "King" & (year == 2008 | year == 2010)
replace treated = 0 if county == "Pierce" & (year == 2008 | year == 2010)
file write myfile _n "Comparing 2008 and 2010" _n
file write myfile "Election Year,Control County,Switched County" _n
foreach i in 2008 2010 {
  local row `i'
  *Control cases.
  qui summ turnoutpct if year == `i' & treated == 0
  local row  = "`row'," + string(`r(mean)',"%9.2f")
  *Switched cases.
  qui summ turnoutpct if year == `i' & treated == 1
  local row  = "`row'," + string(`r(mean)',"%9.2f")
  di "`row'"
  file write myfile "`row'" _n
}
qui count if treated == 0 & year == 2008
file write myfile "N,`r(N)',"
qui count if treated == 1 & year == 2008
file write myfile "`r(N)'" _n
file close myfile
restore

**************************
*Run models separately for each election type.
**************************
local firsttableappend = "replace"
local firsttable = "Table03_CountyModels.out"
local appendixtablecounter = 1
foreach type in "Presidential" "Midterm" "OddYear" {
  preserve
  keep if electype == "`type'"
  qui count
  di ""
  di "==================================================================="
  di "Election type `type': N = `r(N)'."
  di "==================================================================="
  di ""
  
  *Identify first election vbm in this election type.
  sort county year
  by county: gen firstvbm = (vbmonly[_n] != vbmonly[_n-1] & vbmonly[_n] == 1)
  label variable firstvbm "First Election of Type Held All Vote By Mail"
  tab year firstvbm
  
  *Identify second and all other elections of type after first vbm: because 
  *we have so few lagged elections, only an indicator for second plus elections vbm.
  gen secondplusvbm = (vbmonly == 1 & firstvbm == 0)
  label variable secondplusvbm "Second Or More Election of Type Held All Vote By Mail"
  tab year secondplusvbm
  
  *Create year fixed effects and nice labels.
  if ("`type'" == "Presidential" | "`type'" == "Midterm") {
    *Enough observations in presidential and midterms for pre-2000 fixed effects.
    tab year, gen(yr_)
  }
  else {
    *Only fixed effects for 2000 and later elections.
    tab year if year > 1999, gen(yr_)
  }
  drop yr_1
  
  foreach var of varlist yr_* {
    qui summ year if `var' == 1
    label variable `var' "Year = `r(mean)'"
  }
   
  **************************
  *Models.
  **************************
  *One model of registrant count as a proportion of VAP.
  *NOTE: Due to collapsed aged categories in 1996 and 1998, VAP count excludes 18 and 19
  *year olds in these years. Year fixed effects reflect this fact.
  xtreg registeredofvap firstvbm vbmonly yr_*, vce(cluster county2) fe i(county2)
  local repl "append"
  if ("`type'" == "Presidential") local repl "replace"
  outreg using "ModelsRegistrationOfVap.out", se ctitle("`type'") addstat("County Fixed Effects",1) adec(0) bracket rdec(3) 3aster `repl'
  
  local outfile = "TableA0`appendixtablecounter'_Models`type'.out"
  local appendixtablecounter = `appendixtablecounter' + 1
  *Separate dependent variables.
  foreach var of varlist turnoutpct turnoutofvap changeregisteredpct {
    local header: variable label `var'
    *Separate table for registration models.
    if ("`var'" != "turnoutpct") {
      local outfile = "TableA04_AltModels-`var'.out"
      local header = "`header'" + ", `type'"
    }
    
    *Calculate mean absentee turnout rate in two elections prior to first vbm.
    sort county year
    *Create a variable storing the absentee rate in the two elections prior to swtich
      /* old way
      gen thisabsentee = .
      by county: replace thisabsentee = absenteepct if firstvbm[_n+1] == 1 | firstvbm[_n+2] == 1
      *if ("`var'" == "turnoutofvap") {
        **Absentee rate of VAP if that is the response. Not for now.
        *by county: replace thisabsentee = absenteeofvap if firstvbm[_n+1] == 1 | firstvbm[_n+2] == 1
      *}

      *Create a variable that is the mean of thisabsentee by county.
      capture drop priortwoabsrate* *vbmXpriortwo* *thirdpriorabs
      by county: egen priortwoabsrate = mean(thisabsentee)
      label variable priortwoabsrate "Average Proportion Votes Cast Absentee In Two Elections (same type) Prior to Switch"
      *For cases that don't switch within this election type, set priortwoabsrate to rather 0 than missing.
      replace priortwoabsrate = 0 if priortwoabsrate == .
      drop thisabsentee
      */
    capture drop priortwoabsrate* *vbmXpriortwo* *thirdpriorabs lag1abs lag2abs
    by county: gen lag1abs = absenteepct[_n-1]
    by county: gen lag2abs = absenteepct[_n-2]
    gen priortwoabsrate = (lag1abs + lag2abs)/2
    *Re-set priortwoabsrate for post-switch elections to the priortwoabsrate in the first
    *election held all-mail (of that election type).
    by county: replace priortwoabsrate = priortwoabsrate[_n-1] if vbmonly == 1 & firstvbm == 0
    label variable priortwoabsrate "Average Proportion Votes Cast Absentee In Two Elections (same type) Prior to Switch"

    *Less parametric indicators for terciles of priortwoabsrate in year of switch.
    qui centile priortwoabsrate if firstvbm == 1, centile(33 66)
    gen lowerthirdpriorabs = priortwoabsrate < r(c_1)
    gen middlethirdpriorabs = priortwoabsrate >= r(c_1) & priortwoabsrate < r(c_2)
    gen upperthirdpriorabs = priortwoabsrate >= r(c_2)
    label variable lowerthirdpriorabs "Average Proportion Votes Cast Absentee in Lower Tercile"
    label variable middlethirdpriorabs "Average Proportion Votes Cast Absentee in Middle Tercile"
    label variable upperthirdpriorabs "Average Proportion Votes Cast Absentee in Upper Tercile"
    *Set priortwoabsrate to zero for first two elections of type.
    replace priortwoabsrate = 0 if priortwoabsrate == .
    
    *Interaction of vbm and prior two election absentee rate.
      *One interaction with one vbm indicator.
      gen vbmXpriortwo = vbmonly*priortwoabsrate
      label variable vbmXpriortwo "All-Mail*Average Prior Proportion Votes Cast Absentee"
      *Interaction with tercile indicators.
      foreach tvar of varlist *thirdpriorabs {
        local vlab : variable label `tvar'
        gen vbmX`tvar' = vbmonly*`tvar'
        label variable vbmX`tvar' "All-Mail*`vlab'"
      }
      
      *Separate interactions for vbm categories.
      foreach val in first secondplus {
        gen `val'vbmXpriortwo = `val'vbm*priortwoabsrate
      }
      label variable firstvbmXpriortwo "First All-Mail*Average Prior Proportion Votes Cast Absentee"
      label variable secondplusvbmXpriortwo "Second Plus All-Mail*Average Prior Proportion Votes Cast Absentee"
      
    *Interaction of vbm and percent rural.
    capture drop vbmXpctrural
    gen vbmXpctrural = vbmonly*pctrural_md
    label variable vbmXpctrural "All-Mail*County Population Percent Rural 2000 (mean-deviated)"
      
    **************************
    *Selection check: predict newly vbm with prior two absentee rate, all elections.
    **************************
    if ("`var'" == "turnoutpct") {
      local repl2 "append"
      if ("`type'" == "Presidential") local repl2 "replace"
      *Limit to cases that are firstvbm or not vbmonly.
      count if firstvbm == 1 | vbmonly == 0
      reg firstvbm priortwoabsrate pctrural_md if firstvbm == 1 | vbmonly == 0
      outreg using "ModelsPredictNewVBM.out", se ctitle("`type'") bracket rdec(3) 3aster `repl2'
      
      local repl2 "append"
      reg firstvbm priortwoabsrate pctrural_md yr_* if firstvbm == 1 | vbmonly == 0
      outreg using "ModelsPredictNewVBM.out", se ctitle("`type', Year FEs") bracket rdec(3) 3aster `repl2'
    }
    
    *Basic fixed effects version testing for serial correlation in residuals per Wooldridge (2002).
    sort county year
    *Create a year variable that increments by 1.
    by county: gen year2 = _n
    tsset county2 year2
    xtserial `var' vbmonly, output
    local fp = 1 - F(`r(df)',`r(df_r)',`r(F)')
    di " p-value on f-stat: `fp'"
    drop year2
    
    *Basic fixed effects model, one treatment indicator.
    xtreg `var' vbmonly yr_*, vce(cluster county2) fe i(county2)
    if ("`var'" == "turnoutpct" | ("`var'" != "turnoutpct" & "`type'" == "Presidential")) {
      *First dv, first model in each file: addnote and replace; else, append.
      *outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1,"P-Value on Wooldridge Test for Serial Correlation",`fp') adec(6) bracket rdec(3) 3aster replace
      outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster replace
    }
    else {
      *outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1,"P-Value on Wooldridge Test for Serial Correlation",`fp') adec(6) bracket rdec(3) 3aster append
      outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster append
    }
        
    *************************
    *Main body table: turnoutpct, Presidential or Midterm.
    *************************
    if ("`var'" == "turnoutpct") {
      if ("`type'" == "Presidential" | "`type'" == "Midterm") {
        outreg using "`firsttable'", se ctitle("`type', `header'") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster `firsttableappend'
        local firsttableappend = "append"
      }
    }
      
    gen infirstmodel = e(sample)
    di _n "++++Cases not in first model:"
    cl county year if infirstmodel == 0
    di _n "++++"

    *Model with interaction with prior absentee rate, one treatment indicator.
    xtreg `var' vbmonly vbmXpriortwo yr_*, vce(cluster county2) fe i(county2)
    outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster append
    di _n "++++Cases in first model not in second:"
    cl county year if infirstmodel == 1 & e(sample) == 0
    di _n "++++"
    qui drop infirstmodel

    *************************
    *Main body table: turnoutpct, Presidential or Midterm.
    *************************
    if ("`var'" == "turnoutpct") {
      if ("`type'" == "Presidential" | "`type'" == "Midterm") {
        outreg using "`firsttable'", se ctitle("`type', `header'") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster `firsttableappend'
        local firsttableappend = "append"
      }
    }
    
    *Model with interaction with prior absentee rate broken into terciles.
    xtreg `var' vbmX*thirdpriorabs yr_*, vce(cluster county2) fe i(county2)
    qui log using "terciletests.log", text append
    di "`type': `var'" _n "========================================================"
    test vbmXlowerthirdpriorabs = vbmXupperthirdpriorabs
    di "========================================================"
    qui log close
    outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster append
    
    *Basic fixed effects model, multiple treatment indicators.
    xtreg `var' firstvbm secondplusvbm yr_*, vce(cluster county2) fe i(county2)
    test firstvbm = secondplusvbm
    outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1,"P-value on First VBM Greater Than Second Or More VBM",`r(p)') adec(6) bracket rdec(3) 3aster append
    
    *Model with interaction with prior absentee rate, multiple treatment indicators.
    xtreg `var' firstvbm* secondplusvbm* yr_*, vce(cluster county2) fe i(county2)
    test firstvbm = secondplusvbm
    *outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1,"P-value on First VBM Greater Than Second Or More VBM",`r(p)') adec(6) bracket rdec(3) 3aster append
    
    *Model with treatment indicator interacted with percent rural.
    xtreg `var' vbmonly vbmXpctrural yr_*, vce(cluster county2) fe i(county2)
    outreg using "`outfile'", se ctitle("`header'") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster append
    
    ****************
    *Robustness models.
    ****************
    if ("`var'" == "turnoutpct") {
      local repl4 "append"
      if ("`type'" == "Presidential") local repl4 "replace"
      *Model with treatment indicator interacted with percent rural.
      *No direct effect of pctrural because of county fixed effects.
      xtreg `var' vbmonly vbmXpctrural vbmXpriortwo yr_*, vce(cluster county2) fe i(county2)
      outreg using "RobustnessModels", se ctitle("`header', `type', Rural Interaction") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster `repl4'

      *Model only on counties switching post-2004 (i.e. not Pierce, or five rurals).
      xtreg `var' vbmonly yr_* if yearofswitch > 2004 & yearofswitch != ., vce(cluster county2) fe i(county2)
      outreg using "RobustnessModels", se ctitle("`header', `type', Post-2004 Switchers Only") addstat("County Fixed Effects",1) adec(6) bracket rdec(3) 3aster append      
    }
   
    *Lagged turnout as an alternative to the fixed effects.
    if ("`var'" == "turnoutpct") {
      local repl3 "append"
      if ("`type'" == "Presidential") local repl3 "replace"
      *Have to drop the second fixed effect.
      drop yr_2
      *Interact firstvbm and secondplusvbm with lagged turnout.
      gen XfirstvbmXlagged`var' = firstvbm*lagged`var'
      label variable XfirstvbmXlagged`var' "Turnout in Previous Election * First Election of Type Held VBM"
      gen XfirstvbmXlaggedabsentee = firstvbm*laggedabsentee
      label variable XfirstvbmXlaggedabsentee "Absentee Rate in Previous Election * First Election of Type Held VBM"
      gen XsecondplusvbmXlagged`var' = secondplusvbm*lagged`var'
      label variable XsecondplusvbmXlagged`var' "Turnout in Previous Election * Second Or More Election of Type Held VBM"
      *gen XsecondplusvbmXlaggedabsentee = secondplusvbm*laggedabsentee
      *label variable XsecondplusvbmXlaggedabsentee "Absentee Rate in Previous Election * Second Or More Election of Type Held VBM"
      
      reg `var' lagged`var' firstvbm yr_* , vce(cluster county2)
      outreg using "TableA05_ModelsLaggedTurnout.out", se ctitle("`type'") bracket rdec(3) 3aster `repl3'
      local repl3 "append"
      
      reg `var' lagged`var' firstvbm secondplusvbm yr_* , vce(cluster county2)
      outreg using "TableA05_ModelsLaggedTurnout.out", se ctitle("`type'") bracket rdec(3) 3aster `repl3'

      reg `var' lagged`var' firstvbm XfirstvbmX* yr_* , vce(cluster county2)
      *outreg using "TableA05_ModelsLaggedTurnout.out", se ctitle("`type'") bracket rdec(3) 3aster `repl3'
      
      reg `var' lagged`var' firstvbm secondplusvbm XfirstvbmX* XsecondplusvbmX* yr_* , vce(cluster county2)
      *reg `var' lagged`var' firstvbm secondplusvbm XfirstvbmX* yr_* , vce(cluster county2)
      *outreg using "TableA05_ModelsLaggedTurnout.out", se ctitle("`type'") bracket rdec(3) 3aster `repl3'
      
    }   
  }
  restore
}

*Calculate mean absentee turnout rate in two elections prior to first vbm.
sort county year
*Create a variable storing the absentee rate in the two elections prior to swtich
gen thisabsentee = .
by county: replace thisabsentee = absenteepct if newlyvbm[_n+1] == 1 | newlyvbm[_n+2] == 1
*Create a variable that is the mean of thisabsentee by county.
capture drop priortwoabsrate *vbmXpriortwo
sort county year
by county: egen priortwoabsrate = mean(thisabsentee)
label variable priortwoabsrate "Absentee vote rate in two elections prior to switch"
drop thisabsentee
*Year fixed effects.
tab year, gen(yr_)
drop yr_1 
foreach var of varlist yr_* {
  qui summ year if `var' == 1
  label variable `var' "Year = `r(mean)'"
}

*Limit to cases that are newlyvbm or not vbmonly.
count if newlyvbm == 1 | vbmonly == 0
reg newlyvbm priortwoabsrate if newlyvbm == 1 | vbmonly == 0
reg newlyvbm priortwoabsrate yr_* if newlyvbm == 1 | vbmonly == 0
