maryam
maryam

Reputation: 35

Get the variable name that corresponds to the maximum value within an observation

I need to find the variable name that corresponds to the highest value in each observation for a given variable list. I know that I can use egen to get the value itself:

egen newvar = rowmax(v1-vn)

But I don't know how to get the variable name corresponding to the highest value.

Upvotes: 0

Views: 2465

Answers (1)

Aspen Chen
Aspen Chen

Reputation: 735

There might be other ways, but you can build on the egen results. Here is an example looping through the variables to find variable(s) with the maximum values.

// generate random data
clear
set obs 10
forval i=1/5    {
    gen r`i'=round(10*runiform())
}

egen maxval=rowmax(r1-r5)  // find maximum value
gen str20 maxvar="" // create string variable to store matched results

// find variables with the same value as maxval and add them to maxvar
foreach var of varlist r1-r5    {
    replace maxvar=maxvar+" "+"`var'" if maxval==`var'
}

list

Upvotes: 3

Related Questions