phlinowl
phlinowl

Reputation: 13

Stata: save name of variable with max value as a string

I have several variables in the same row: x1 x2 x3 x4

With egen and the rowmax function, I create a new variable containing the value the x* with the highest value:

egen max_x = rowmax(x1 x2 x3 x4)

However, instead of saving the maximum value, I would like to save the name of the variable which contains the maximum value as a string. How can I do that?

Upvotes: 1

Views: 877

Answers (1)

ChrisP
ChrisP

Reputation: 5952

There might be a single command for this, but here is one approach...

// generate some test data
set obs 10
forvalues i=1/4 {
    gen float x`i' = runiform()
}

tempvar valmax argmax
gen `valmax' = x1
gen `argmax' = "x1"
foreach v of varlist x2-x4 {
    // does value beat the current highest value?
    replace `argmax' = "`v'" if `v' > `valmax' & !mi(`v')
    replace `valmax' = max(`valmax', `v')
}

list

You should also consider how ties and missing values are handled.

Upvotes: 2

Related Questions