/***************************************************************************************************************** SAS file name: hash_sum.sas File location: __________________________________________________________________________________________________________________ Purpose: To demonstrate how to use the hash object to calculate by-group sums and cummulative sums with the SAS hash object Author: Peter Clemmensen Creation Date: 22/10/2020 This program supports the blog post "Calculate Sums With The Hash Object in SAS" on SASnrd.com *****************************************************************************************************************/ /* Example data */ data have; input id \$ x; datalines; 002 2 003 5 003 1 001 5 002 9 001 6 001 3 002 4 003 7 ; /* By-Group sums with the hash object */ data want; if _N_ = 1 then do; dcl hash h(); h.definekey('id'); h.definedata('s'); h.definedone(); do until (z); set have end = z; if h.find() ne 0 then s = 0; else s + x; h.replace(); end; end; set have; h.find(); run; /* Create summary table with the hash object */ data _null_; dcl hash h(); h.definekey('id'); h.definedata('id', 's'); h.definedone(); do until (z); set have end = z; if h.find() ne 0 then s = 0; s + x; h.replace(); end; h.output(dataset : 'want'); run; /* equivalent to */ proc summary data=have nway; class id; var x; output out=want(drop=_:) sum=; run; /* Cumulative sums with the hash object */ data want; if _N_ = 1 then do; dcl hash h(); h.definekey('id'); h.definedata('cs'); h.definedone(); end; set have; if h.find() then cs = x; else cs = sum(cs, x); h.replace(); run; /* Using Suminc */ data want; if _N_ = 1 then do; dcl hash h(suminc : 'x'); h.definekey('id'); h.definedone(); end; set have; h.ref(); h.sum(sum : cum_sum); run; data _null_; call symputx('year', 03); y = 20&year; put y=; run;