data have; input id var1 var2; cards; 1 3 . 1 5 . 1 . 4 1 . 7 2 4 2 2 8 . 2 . 8 2 9 . 2 . . 3 2 3 3 7 . 3 . 9 3 . 6 4 . 2 5 . 1 5 9 2 6 . 5 6 . 3 run; If the missing value is not at the beginning of each ID, then the missing values equal to lag non-missing value; If the missing value is at the beginning of each ID, and no non-missing values after the missing value, then the missing values equal to 0. E.g., for ID=4 and ID=6; If the missing value is at the beginning of each ID, and there exist non-missing values after the missing value, then the missing values equals to forward non-missing value; e.g., for ID=5, the missing value for var1 should be replaced by 9, rather than 7 (which is for ID=3) or 0 (which is for ID=4). I was thinking to generate two new variables, e.g., variable “count” to count by ID, and variable “total” represents total observations for each ID, use those two new variables as conditions for different missing value replacement. However, look-ahead replacement is out of my reach. I also find some answers online, but not exactly what I want, like the following one is replacing all missing values with lag values. https://communities.sas.com/t5/SAS-Procedures/Replacing-missing-values-by-previous-observation/td-p/26707 data want; set have; n=_n_; if missing(var1) then do; do until (not missing(var1)); n=n-1; set have(keep= var1) point=n; *second SET statement; end; end; run; Desired output: Thanks!
... View more