Create variable by dividing variable by IQR in Stata

How can I create a variable by dividing it by IQR? I have come a long way in the following way.

Sample data and code:

use http://www.ats.ucla.edu/stat/stata/notes/hsb2, clear

foreach var of varlist read-socst {
   egen `var'75 = pctile(`var'), p(75)
   egen `var'25 = pctile(`var'), p(25)
   gen `var'q =`var'75 - `var'25
   drop `var'75 `var'25
}

gen readI = read/readq
gen sciI = science/scienceq

      

+3


source to share


1 answer


The easiest way is to just use the results summarize

directly:

sysuse auto, clear

quietly foreach v of var price-foreign { 
    su `v', detail 
    gen `v'q = `v' / (r(p75) - r(p25)) 
} 

      

A route egen

is overkill if it means creating new variables for each original variable, just to keep quartiles or IQRs as duplicate constants. But it egen

comes to life when you want to do it in groups:



bysort foreign: egen mpg_upq = pctile(mpg), p(75)
by foreign: egen mpg_loq = pctile(mpg), p(25)
gen mpg_Q = mpg / (mpg_upq - mpg_loq)

      

Note that IQR can be 0 and often will be 0 for indicator variables.

+2


source







All Articles