As the first step in the decommissioning of the site has been converted to read-only mode.

Here are some tips for How to share your SAS knowledge with your professional network.

Returning Zip Codes in a Specified Radius

From sasCommunity
Jump to: navigation, search

I just saw the macro maven's posting Calculating Distance Between Two Zip Codes and thought I'd throw in a macro that I use to return a set of zip codes within a given radius of a base zip code.

 Purpose : Returns zipcodes within x miles of a given zipcode.
 Inputs  : sashelp.zipcode
 Outputs : SAS dataset of found zipcodes
 Notes   : base - starting zip code.
           dist - radius of search area in miles (default = 10).
           libout - target output library (default=work).
           dsnout - target output dataset (default=zip#####_r###).
 %macro ZipsNear(base=,dist=10,libout=work,dsnout=zip&base.r&dist.)
       /des='Returns zipcodes within x miles of a given zipcode.';
   %if &base eq %str() %then
     %put %nrstr(%%)ZipsNear parameters:;
     %put %str( %()base  = Base Zipcode,;
     %put %str(  )dist   = Radius from base,;
     %put %str(  )libout = Output library,;
     %put %str(  )dsnout = Output dataset%str(%));
     %goto Quit;
   proc sql noprint;
     %* fetch latitude and longitude of base zip code *;
     select y, x into :lat, :lon
     from   sashelp.zipcode
     where  zip=&base ;
     %* fetch zips within specified distance from base zip code *;
     create table &libout..&dsnout. as
       put(zip,z5.) as ZipText,
       3956 * (2 * arsin(min(1, sqrt((sin(((y - &lat) * constant('pi')/180)/2)**2) + ((cos(&lat * constant('pi')/180)) * (cos(y * constant('pi')/180)) * (sin(((x- &lon) * constant('pi')/180)/2)**2)))))) as distance
       calculated distance <= &dist
     order by zip;
 %mend ZipsNear;

I regularly use it for drawing samples from a given metropolitan area.

--RichardK 12:37, 14 September 2007 (EDT)