Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: selecting subsets of data based on date with which to calculate geonear (SSC)

From   "Ben Hoen" <>
To   <>
Subject   st: selecting subsets of data based on date with which to calculate geonear (SSC)
Date   Fri, 21 Dec 2012 15:03:51 -0500

Happy Holidays!

I am trying to find a way to loop through cases in a file, while selecting a
subset of that file (based on date) with which I would execute a
geonear(SSC) calculation with them. Specifically, for each case in the file,
I would like to select the nearest 5 neighbors that have a date which is
equal to or within the preceding 6 months.

I have some comfort with how to execute the geonear(SSC) part of it, but
seem to be lost with how to select subsets of data based on a particular

Here is my (feable) attempt to build this code.  I (clearly) nonplussed how
to do what I hope to do, but figure there are many examples.  If you have
any advice, links, etc, I would be greatly appreciative.

Best wishes for the holidays.  



set seed 1234
sysuse auto, clear
gen ylat = 41+runiform()  //to create a latitude
gen xlong = -73-1*runiform() //to create a longitude
gen date=16500+(int(500*runiform())) //to create dates that a within a few
years of each other
format date %tdnn/dd/YY
g id=_n //to create an id
keep id ylat xlong date price
order id price date ylat xlong

tempfile all nnset tempest  //to create temp files to be used in the loop
save "`all'" //saving the full dataset
g emptyvar=. //to create a empty variable so I can save an empty dataset
save "`tempset'" // saving off the empty dataset

local N=_N //to establish the number of cases

forvalues i = 1/N { //I am trying here to begin a loop through the cases
	local maxdate=date
	local mindate=date-180
	keep if date>=`mindate' & date <=`maxdate' // my attempt to select a
group of cases
	save "`nnset'" // and to save off that group
	geonear id ylat xlong using `nnset', n(id xlong ylat) ignore
nearcount(5) miles //store info about the 5 nearest neighbors from the
	append using "`tempset'" //append the case to the temp file

Ben Hoen
Principal Research Associate
Lawrence Berkeley National Laboratory
Office: 845-758-1896
Cell: 718-812-7589

Visit our publications at:

*   For searches and help try:

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