Announcement

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

  • Generating a new variable that is the variable with the max value from rowmax

    Hello and thank you!
    I am trying to generate a new variable that is the variable with the max value among a list of 8 variables. When I use the egen command with a rowmax function is it possible to list which variable within my list is variable for the max value? I'ld like to create this new variable across observations.

    For example,

    id v1 v2 v3 v3 v4 v5
    1 0 2 1 9 7 8
    2 1 1 2 3 4 6
    3 9 8 7 6 5 4

    For this new variable I would like it to generate it as such:

    id max_v
    1 v3
    2 v5
    3 v1

    My current problem is that the roxmax is returning just the numeric maximum for each observation rather than which variable within my list of variables is the maximum. Any and all help would be amazing.

  • #2


    The difficulty is what happens if you have ties. That is a good reason why there isn't a sibling in official Stata to egen, rowmax() that names the variable with a maximum. In your examples, you have ties for minimum so ties for maximum don't seem ruled out.

    Code:
    egen rowmax = rowmax(v1-v5)
    gen which = .  
    
    forval j = 1/5 {
          replace which = `j'  if v`j' == rowmax & which == .
    }
    identifies the first variable met with a maximum while the same code with

    Code:
    replace which = `j'  if v`j' == rowmax
    identifies the last variable met.

    See https://www.stata-journal.com/articl...ticle=pr0046_1 for a much fuller discussion.

    If you don't have access and wish to see a copy, then send me an email by personal message for a reprint.

    (Someone will point out that this is also possible after a reshape long.)

    Comment

    Working...
    X