/***************************************************************************************************************** SAS file name: mean_impute_hash.sas File location: __________________________________________________________________________________________________________________ Purpose: To demonstrate mean imputation using the SAS hash object. Author: Peter Clemmensen Creation Date: 21/12/2020 This program supports the blog post "Mean Imputation in SAS Using the Hash Object" on SASnrd.com *****************************************************************************************************************/ /* Example data */ data have; input ID v; datalines; 1 2 1 3 1 4 2 1 2 2 2 3 3 6 3 4 3 5 ; /* Calculate Means with Proc Summary */ proc summary data=have nway; class id; var v; output out=mean_summary(drop = _:) mean=; run; /* Calculate Means For v1 and v2 */ data _null_; dcl hash h(ordered : "A"); h.definekey("id"); h.definedata("id", "n", "s", "m"); h.definedone(); do until (z); set have end = z; call missing(n, s); rc = h.find(); if v then do; n + 1; s + v; m = divide(s, n); h.replace(); end; end; h.output(dataset : "mean_hash(drop = n s)"); run; /* Mean imputation Using the Hash Object*/ /* Example Data */ data have; input ID v; datalines; 2 2 1 2 2 . 3 5 1 4 2 1 3 4 1 . 2 3 1 3 3 . 3 6 ; /* Mean Imputation Using Hash Object */ data want(drop = s n rc); dcl hash h(ordered : "A"); h.definekey("id"); h.definedata("id", "n", "s", "v"); h.definedone(); do until (z1); set have end = z1; call missing(n, s); rc = h.find(); if v then do; n + 1; s + v; v = divide(s, n); h.replace(); end; end; do until (z2); set have end = z2; if v = . then h.find(); output; end; run;