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

# st: if-then-else

 From Christopher F Baum To statalist@hsphsun2.harvard.edu Subject st: if-then-else Date Wed, 17 Dec 2003 23:12:11 -0500

On Wed, 17 Dec 2003, Richard Williams wrote:
> In SPSS, I could do something like
>
> DO IF X1 = 1 and X2 = 3
> Compute Y = 3.
> ELSE IF X3 = 2 and X4 = 17
> Compute Y = 4.
> ELSE
> Compute Y = 5.
> END IF.

Although Richard's point--that most programming languages contain an if-then-else structure--this example shows one of the potential confusions of that structure. What if (x1/x4) = (1,3,2,17) ? In this example, that will yield y=4; the order of the if-else clauses matters. Perhaps this is not very likely to be a realistic application of if-then-else--more likely that the conditions are mutually exclusive--but whether one programs this as if-then-else or, as in Stata, as successive 'replace if' statements, the ordering of these evaluations matters.

And for an obtuse solution:

. g c1=3*(x1==1 & x2==3)

. g c2=4*(x3==2 & x4==17)

. g y= cond(max(c1,c2),max(c1,c2),5)

. list x1-x4 y

+-----------------------+
| x1 x2 x3 x4 y |
|-----------------------|
1. | 1 3 0 0 3 |
2. | 0 0 2 17 4 |
3. | 1 2 3 4 5 |
4. | 1 3 2 17 4 |
5. | 1 2 3 4 5 |
+-----------------------+

Kit

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