Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: loop thru unique values of a variable

From   Philip Ryan <>
Subject   Re: st: loop thru unique values of a variable
Date   Sat, 07 Sep 2002 12:11:55 +0930

bysort D: <stata command>

This construct in Stata often solves problems that other programs require looping structures to address.

As an aside, -inspect- is not a good choice for finding the number of unique values of a variable. It only reports up to 99 unique values, after which r(N_unique) is set to missing. -tabulate- is theoretically good for up to 3000 unique values [see r(r) after a -return list- ]. There was a thread on the list some time ago about what to do when the number of unique values was greater than 3000; the archives would have this. I suspect some looping would be involved.


At 05:32 PM 6/09/2002 -0700, you wrote:

Hi all !

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 ?

Thanks for any suggestions ,


Matt Schonlau
310-393-0411 x7682

* For searches and help try:
Philip Ryan
Associate Professor and Head,
Department of Public Health
Medical School
University of Adelaide
Adelaide 5005
South Australia

tel: +61 8  83033570
fax: +61 8 82234075

*   For searches and help try:

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