# RE: st: loop thru unique values of a variable

 From "Nick Cox" To Subject RE: st: loop thru unique values of a variable Date Mon, 9 Sep 2002 14:49:56 +0100

```Matt Schonlau asked

>I am trying to loop through all unique values of a variable.
>
>For example if the data set contains 9 observations and the variable
of
>interest is D which takes the values 0 0 0 2 2 2 4 4 4
>I would like to loop through the unique values 0 2 4  .
>
>Below is a terrible "fix" which makes the additional assumption that
the
>unique values are evenly spaced. ( I prefer not to make that
assumption).
>It basically extracts the number of unique values from *inspect*,
finds
>the minimum value through *summarize* and then constructs the loop
from
>scratch .
>
>quietly inspect D
>local nu=r(N_unique)
>quietly sum D
>local dmin = r(min)
>local last = `nu' * `dmin'
>
>forvalues d= `dmin'(`dmin') `last' {
>...
>}
>
>Is there a better way to do that in stata or is that just not what
stata
>was built for ?

Roger Newson replied

>
> I would use Nick Cox's -vallist- package, downloadable from SSC. In
> Web-aware Stata, type -findit vallist- or -ssc describe
> vallist- to find
> out more.
>
> For instance, Matt might type
>
> vallist D
> local values "r(list)"
> foreach d of numlist `values' {
> ...
> }
>
> where ... again stands for whatever Matt wanted to do for
> each value.
>

I consider -vallist- (STB-60, updated on SSC) to be superseded
by -levels-
(SSC). Loosely speaking, -levels- does less, but it marks a retreat
to the main idea behind -vallist- and is designed to work more
obviously
and more smoothly with -foreach-. The difference may seem
small from a translation of Roger's example

levels D, local(values)
foreach d of local values {
...
}

but there are good reasons why this is slightly better style.

Is there a way to tell Stata to try all values of a particular
variable
in a -for- statement without specifying them?
http://www.stata.com/support/faqs/data/for.html

Nick
n.j.cox@durham.ac.uk

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