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   Roger Newson <[email protected]>
To   [email protected]
Subject   Re: st: loop thru unique values of a variable
Date   Sun, 08 Sep 2002 17:59:07 +0100

At 17:32 06/09/02 -0700, Matt Schonlau 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 ?
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 hope this helps.

Roger


--
Roger Newson
Lecturer in Medical Statistics
Department of Public Health Sciences
King's College London
5th Floor, Capital House
42 Weston Street
London SE1 3QD
United Kingdom

Tel: 020 7848 6648 International +44 20 7848 6648
Fax: 020 7848 6620 International +44 20 7848 6620
or 020 7848 6605 International +44 20 7848 6605
Email: [email protected]

Opinions expressed are those of the author, not the institution.

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




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