Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: multiple ifs- a better example


From   "Rajesh Tharyan" <[email protected]>
To   <[email protected]>
Subject   st: multiple ifs- a better example
Date   Fri, 29 Jun 2007 13:24:23 +0100

Hi,

This relates to my earlier question on nested if statements

This one uses the auto file ..

I classify cars into 25 groups based on quintiles of mpg and length. First I
form quintiles of mpg then for each of those I form quintiles of length. Now
I append another car to the dataset say

car     mpg  length
maruti   50   125

How can I allocate this car to the appropriate group? (where group is a
combination of quintile number of mpg (mc) and weight(bm))

below is my code for generating the quintiles and calculating the maximum
and minimum values for the two variables mpg and length.

**************stata code************

sysuse auto,clear
keep make mpg length

* create quintiles of mpg
sort  mpg
xtile mc=mpg,nq(5)

* for each quintile of mpg create quintiles of length
gen bm=.
levels mc, local(levels)
foreach i of local levels {
xtile bm_`i'=length if mc==`i',nq(5)
replace bm=bm_`i' if mc==`i'
drop bm_`i'
compress
}

* create the group as a combination of mc and bm
* a represents the group (looks like 11,12,13 etc)

tostring bm mc,replace
gen a=mc+bm
list in 1/10


levels a,local(levels)
foreach i of local levels {
egen m_max`i'=max(mpg) if a=="`i'"
egen m_min`i'=min(mpg) if a=="`i'"
egen b_max`i'=max(length) if a=="`i'"
egen b_min`i'=min(length) if a=="`i'"
replace m_max`i'=m_max`i'[_n-1] if m_max`i'>=.
replace m_min`i'=m_min`i'[_n-1] if m_min`i'>=.
replace b_max`i'=b_max`i'[_n-1] if b_max`i'>=.
replace b_min`i'=b_min`i'[_n-1] if b_min`i'>=.
}


levels a,local(levels)
foreach i of local levels {
replace m_max`i'=m_max`i'[_N] 
replace m_min`i'=m_min`i'[_N] 
replace b_max`i'=b_max`i'[_N] 
replace b_min`i'=b_min`i'[_N] 
}

* append the new company here 
* fillin the max values for mpg and length here

levels a,local(levels)
foreach i of local levels {
replace m_max`i'=m_max`i'[1]
replace b_max`i'=b_max`i'[1]
replace m_min`i'=m_min`i'[1]
replace b_min`i'=b_min`i'[1]
}

* get the appropriate mc and bm if mc & bm==.

*******end code**********

I figure that the allocate will involve multiple ifs but I am not sure how
to code it..

Any help appreciated

Thanks very much
rajesh

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index