Danielle H. Ferry
>
> Is there a command similar to -levels- that works across a varlist?
> Specifically, suppose I have the variables highrisk1,
> highrisk2, lowrisk1,
> lowrisk2, lowrisk3. I want to write a program with a loop that does
> something when highrisk==1, then when highrisk2==1, then
> when lowrisk1==1,
> then when lowrisk2==1, and finally when lowrisk3==1. For example:
>
> -----------------------------
> program define example
>
> forval i = 1(1)2 {
> ta year if `1'`i'==1
> }
>
> end
>
> example highrisk
> example lowrisk
> -----------------------------
>
> Since there are 2 highrisk variables and 3 lowrisk
> variables, the way I've
> written it, this will miss tabulating when lowrisk3==1. If
> I make the second
> line: "forval i = 1(1)3 {" then Stata will object when it gets to
> "highrisk3==1" since highrisk3 doesn't exist. Something
> similar to -levels-
> would enable Stata to figure out what the max on `i' should be.
>
Two quick answers:
1. Yes, but
2. You don't need one for this problem,
for which other approaches are better.
In more detail,
2.
foreach v of var highrisk* lowrisk* {
tab year if `v' == 1
}
That is, you let -foreach- unpack the varlist
with which it is supplied.
(Perhaps there is a neater wildcard, e.g. *risk*)
1. You could do this
unab varlist : highrisk* lowrisk*
foreach v of local varlist {
tab year if `v' == 1
}
No apparent advantages here, but often useful
elsewhere.
Similarly, you could do this
ds highrisk* lowrisk*
foreach v in `r(varlist)' {
tab year if `v' == 1
}
Similar comment. Note especially
various filters which can be added
to -ds-. (Update 17 June 2003)
Nick
[email protected]
*
* 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/