clear
set more off

********************************************************************************
********************************************************************************
*	Import 2014 election data
********************************************************************************
********************************************************************************

* Municipalities with more than 1000 inhabitants
********************************************************************************

import delimited "$source\elections\muni-2014-resultats-com-1000-et-plus-t1.txt", delimiter(";") varnames(1) clear

duplicates report codedudépartement codedelacommune
assert r(unique_value) - r(N) == 0 // Check absence of duplicates

renvars codedudépartement libellédudépartement codedelacommune inscrits votants \ departement_code departement_name commune_code voters votes
keep departement_code departement_name commune_code voters votes

tempfile tmp1
save `tmp1', replace

* Municipalities with less than 1000 inhabitants
********************************************************************************

import delimited "$source\elections\muni-2014-resultats-com-moins-1000-t1.txt", delimiter(";") varnames(1) clear

duplicates drop coddpt codsubcom, force // Data has several lines per municipality (1 per candidate)

renvars coddpt libdpt codsubcom nbrins nbrvot \ departement_code departement_name commune_code voters votes
keep departement_code departement_name commune_code voters votes

* Apppend both groups of municipalilties
********************************************************************************

append using `tmp1'

duplicates drop departement_code commune_code, force  // Some municipalities of French POlynesia appear in both groups (data are consistent)

* Sum voters and votes by department
********************************************************************************

collapse (sum) voters votes, by(departement_code departement_name)

* Compute turnout at the department level
********************************************************************************

gen turnout = votes/voters

summ turnout
assert inrange(r(min),0,1)
assert inrange(r(max),0,1)

* Harmonize departement identifier
********************************************************************************

replace departement_code = "971" if departement_code == "ZA"
replace departement_code = "972" if departement_code == "ZB"
replace departement_code = "973" if departement_code == "ZC"
replace departement_code = "974" if departement_code == "ZD"
replace departement_code = "976" if departement_code == "ZM"
replace departement_code = "988" if departement_code == "ZN"
replace departement_code = "975" if departement_code == "ZS"
replace departement_code = "987" if departement_code == "ZP"

* Save
********************************************************************************
compress
save "$temp/departement_turnout_2014", replace
