Re: st: Generating multiple variables

 From David Kantor <[email protected]> To [email protected] Subject Re: st: Generating multiple variables Date Wed, 05 Sep 2007 17:11:46 -0400

```At 04:52 PM 9/5/2007, Georgiana wrote:
```
```Hi. I would like to generate and code multiple variables with similar
names (beginning with limitdur*) based on multiple variables with similar
names. The laborious way to do it is:

generate limitdur1=0
replace limitdur1=lhcaly1 if ladura1 == .
replace limitdur1=ladura1 if lhcaly1 == .

generate limitdur2=0
replace limitdur2=lhcaly2 if ladura2 == .
replace limitdur2=ladura2 if lhcaly2 == .

generate limitdur3=0
replace limitdur3=lhcaly3 if ladura3 == .
replace limitdur3=ladura3 if lhcaly3 == .

and so on...

Is there an easier way to do this?
[...]
```
Sure.
How many of these are there? I will suppose that it is 20 for demonstration purposes.

forvalues j = 1/20 {
generate limitdur`j'=0
replace limitdur`j'=lhcaly`j' if ladura`j' == .
replace limitdur`j'=ladura`j' if lhcaly`j' == .
}

Notice that `j' takes the place of the suffix digit on all the variables.

Note that there are other ways of coding the body of the loop, in particular, using cond():
#delimit ;
gen limitdur`j' =
cond(lhcaly`j' == . , ladura`j' ,
cond(ladura`j' == . , lacaly`j' ,
0));

And there may be other ways as well, depending on the logic of the situation, which I will not go into now.

Finally, be aware that "==." tests for one specific missing value. Is that what you want? The more general way to test for (any) missing value is with the missing() (or mi()) function, as in mi(ladura`j' ).

HTH
--David

*
* 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/