Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Loop for weighted median

    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

  • #2
    Code:
    summarize EC_EU_positive [w=vote_share] if countryname == "Belgium" & year == `i', detail

    Comment


    • #3
      The user contributed egen function -wpctile(varname)-, part of the egenmore package, can calculate you a weighted median. (The 50th percentile is the median.)

      Type

      Code:
      . findit egenmore
      and follow the instructions to install it.

      Comment


      • #4
        The error in #1 arises in repeating the syntax element if and as such is not a reflection of your dataset, either what is or what it is not.

        Comment


        • #5
          Thanks, egenmore worked perfectly!
          And thanks for the correction to the loop

          Comment

          Working...
          X