> -----Original Message-----
> From: Richard Herrell [mailto:[email protected]]
> Sent: Thursday, September 19, 2002 3:27 PM
> To: statalist
> Subject: st: newbie if {} else {} question
>
>
> I've just started learning Stata syntax after long years of
> SAS use and am
> completely stumped by a result. I want to create a new
> 4-level variable
> (ascertgp) based on the crosstabulation of 2 dichotomous
> variables (probip
> and promig). This is the syntax I wrote:
>
> if probip==1 & promig==1 {
> gen ascertgp=1
> }
> else if probip==0 & promig==1 {
> gen ascertgp=2
> }
> else if probip==1 & promig==0 {
> gen ascertgp=3
> }
> else if probip==0 & promig==0 {
> gen ascertgp=4
> }
>
> When I run tab1 ascertgp I get a value of 3 for every observation. (I
> know what the 4 frequencies should be from the crosstab.) I
> must be doing
> something very obviously wrong, but can see what it is.
In Stata, the "if {} else {}" construct applies to blocks of code, not
to individual
observations. You want to use the "if" clause within the generate
command:
. gen ascertgp=1 if probip==1 & promig==1
. replace ascertgp=2 if probip==0 & promig==1
. replace ascertgp=3 if probip==1 & promig==0
. replace ascertgp=4 if probip==0 & promig==0
The "if" here says "apply this command only to the observations
indicated". You can use "if" in the exact same sense for most commands;
for example, to restrict the estimation sample for a command, or
whatever.
In your code above, Stata is evaluating each condition, and then either
executing or not executing the code within the {}, *for all
observations*. Unless told otherwise, it evaluates the variables in the
expression in terms of the first observation in your dataset; apparently
for that observation, probip is 1 and promig is zero.
By the way, there are probably easier ways to generate your summary
variable:
. egen ascertgp = group(probip promig)
will do it, albeit with a different coding. See "help egen" for more
information on the goodies included with egen (Extended GENerate). The
following will do it with your coding, although it is a much less
generalizable solution:
. gen ascertgp = 2*(1-probip) + (1-promig) + 1
Welcome to Stata. Once you get used to the syntax, you won't go back.
--Nick Winter
*
* 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/