Friday, March 1, 2013

SAS: Hash table example

A co-worker came up with a cool example of hash table usage in SAS.  Modified slightly and shown here:

data location;
   input Loc $ LocName $ LocState $ LocZip;
   datalines;
AA Ankorage AL 12345
BB Boise    ID 67890
CC Cisco    CA 65432
;
proc print data=location;
   title 'Location';
run;

/*=============== some shift data ===================*/
data shift;
   input EmpID Date yymmdd10. Hours Loc $;
   format Date yymmdd10.;
   datalines;
11 2012-04-03 19 AA
22 2012-04-03 11 BB
33 2012-04-03 12 CC
;
proc print data=shift;
   title 'Shift';
run;

/*=============== some score data ===================*/
data score;
   input EmpID Date yymmdd10. score ;
   format Date yymmdd10.;
   datalines;
11 2012-04-03 900
22 2012-04-03 555
33 2012-04-03 888
44 2013-02-28 999
;
proc print data=score;
   title 'Score';
run;

/*=============== sort the data ===================*/
/*==  no need to sort location since it       =====*/
/*==  is merged using a hash object           =====*/

proc sort data=shift;
   by EmpID Date;
run;
proc sort data=score;
   by EmpID Date;
run;

/*=============== merge it     ===================*/
data merged;
    merge shift score;
    by EmpID Date;

    /* get the location data with a hash table */
    format LocName $20.;
    format LocState $2.;
    if _N_ = 1 then do;
        declare hash h(dataset: "work.location");    /* create the object */
        h.defineKey('Loc');                          /* define the Key  */
        h.defineData('LocName', 'LocState');         /* define the Data */
        h.defineDone();                              /* this loads it   */
        end;
    rc = h.find();
    if (rc > 0) then LocName ='?';

    score    = coalesce(score,0);
    Hours    = coalesce(Hours,0);

proc print data=merged;
   title 'Merged';
run;




No comments:

Post a Comment