Announcement

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

  • Assign specific value in Ranked Column if...

    Good afternoon,

    I am ranking across 2 variables, score_1 and score_2 by raceid, using the code below.

    If the score returned in score_1 or score_2 is 0 (zero), I need the value of -1 to be returned in the relevant rank columns, not 11 as it is now.

    Here is the code that I am currently using...

    sort raceid
    foreach v in score_1 score_2{
    by raceid: egen rank_`v' = rank(-`v'),track
    }

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input byte(raceid score_1 score_2) float(rank_score_1 rank_score_2)
    1 10 10  1  1
    1  9  9  2  2
    1  8  8  3  3
    1  7  6  4  5
    1  6  7  5  4
    1  5  5  6  6
    1  4  4  7  7
    1  3  3  8  8
    1  2  2  9  9
    1  1  1 10 10
    1  0  0 11 11
    end
    Thank you,
    Hans

  • #2
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte(raceid score_1 score_2)
    1 10 10
    1  9  9
    1  8  8
    1  7  6
    1  6  7
    1  5  5
    1  4  4
    1  3  3
    1  2  2
    1  1  1
    1  0  0
    end
    
    forvalues i = 1/2 {
        egen rank_`i' = rank(score_`i') if score_`i' != 0, field
        replace rank_`i' = -1 if score_`i' == 0
    }
    Code:
         +----------------------------------------------+
         | raceid   score_1   score_2   rank_1   rank_2 |
         |----------------------------------------------|
      1. |      1        10        10        1        1 |
      2. |      1         9         9        2        2 |
      3. |      1         8         8        3        3 |
      4. |      1         7         6        4        5 |
      5. |      1         6         7        5        4 |
         |----------------------------------------------|
      6. |      1         5         5        6        6 |
      7. |      1         4         4        7        7 |
      8. |      1         3         3        8        8 |
      9. |      1         2         2        9        9 |
     10. |      1         1         1       10       10 |
         |----------------------------------------------|
     11. |      1         0         0       -1       -1 |
         +----------------------------------------------+

    Comment

    Working...
    X