Good morning,
I have a dataset containing indicators for each country for each election year. The indicator I am interested in is EC_EU_positive, which assigns a value between 1 and 10 to every party that ran for election in a country in an election year.
I am interested in calculating the weighted mean and median, for each country and for each election year, of the variable EC_EU_positive. The weights are given by the vote shares of the parties that ran for that election.
For the weighted mean I used the following code:
ssc install _gwtmean
bysort countryname year: egen EC_EU_positive_weighted_mean=wtmean(EC_EU_positive ), weight(vote_share)
And it seems to work.
However, I have trouble calculating the weighted median. As far as I am aware, there is no specific command, so I tried with the following loop:
gen wtmedian = .
levelsof year, local(el_year)
foreach i in `el_year' {
summarize EC_EU_positive [w=vote_share] if countryname == "Belgium" & if year == `i', detail
replace wtmedian = r(p50) if countryname == "Belgium" & if year == `i'
}
But, when I run it, I get the error message “if not found” r(111). I suspect that this is due to the fact that we don’t have elections every year, so the loop finds some missing values.
Does anybody know a way to solve this issue?
Thanks in advance