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

st: by & nearest


From   Benoit Dulong <[email protected]>
To   statalist <[email protected]>
Subject   st: by & nearest
Date   Fri, 22 Aug 2003 11:54:00 -0400

Is it possible (change the program) to get nearest to work with by ?

I can not find the answer in my NC151 notes.

Thank you

Benoit Dulong.


**********************************************************************

. set obs 100
obs was 0, now 100

. gen idrep = _n

. genpoisson n1, mu(20)

. genpoisson n2, mu(40)

. gen n = n1+n2

. expand n
(5917 observations created)

. sort idrep

. gen x = uniform()

. gen y = uniform()

. by idrep: nearest x y, id(idpoint) dist(h)
nearest may not be combined with by
r(190);

end of do-file
r(190);

**********************************************************************

program def nearest
*! NJC 1.1.0 10 January 2003
    version 7 
    syntax varlist(min=2 max=2 numeric) [if] [in] , dist(str) [id(str)]
    confirm new var `dist'
    
    if "`id'" != "" {
        confirm new var `id'
    }     
    else local noid "*"
    
    marksample touse
    tokenize `varlist'
    args x y 

    qui { 
        gen double `dist' = .
        `noid' gen long `id' = .
        tempname d
        local n = _N
        
        forval i = 1/`n' {
            forval j = 1/`n' {
                if `touse'[`i'] & `touse'[`j'] & (`i' != `j') {
                    scalar `d' = /*
            */ (`x'[`i'] - `x'[`j'])^2 + (`y'[`i'] - `y'[`j'])^2
                    if `d' < `dist'[`i'] {
                        replace `dist' = `d' in `i'
                        `noid' replace `id' = `j' in `i'
                    }
                }
            }    
        }
        replace `dist' = sqrt(`dist')
        `noid' compress `id'
    } 
end 

**********************************************************************

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