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
Replace value in one row based on another variables ID year open near_2 near_3 competition exposed 1 2005 1 1 1 0 0 1 2006 1 1 1 0 1 1 2007 1 1…
Need help creating tex table by two variablesI would like to create a table that includes the mean and standard deviation of a group of variables…
guidance on minimum sample size for 'medsem' packageMy understanding was that SEM typically requires a larger sample size, ideally over 200 observations…
Reshape ProblemDear Statalist, I downloaded data from the UN National Accounts. Unfortunately the layout of the da…
Nesting foreach loops within a while loopI am trying to create a foreach loop within a while loop, and the issue is that the foreach loop exe…
Subscribe to:
Post Comments (Atom)
0 Response to Loop for weighted median
Post a Comment