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
Related Posts with Loop for weighted median
Coloring bars by group- asyvars alternative?I am trying to color bars based on the values of a categorical variable As described here: https://…
A Statalist glossary This is a revision of a glossary that appeared on 1 January 2011. Striking (to me any way) that mos…
Multiple imputation problemThis is a specific problem emerged in my previous post "Reshape wide". The data are the following: …
inter-rater reliability and iccHi all, I am trying to calculate inter-rater reliability with a complicated study and data structur…
Concatenating variables as a function of other variablesDear all, I have a database comprised of an id variable (siteid), two variables that indicate the l…
Subscribe to:
Post Comments (Atom)
0 Response to Loop for weighted median
Post a Comment