BookmarkSubscribeRSS Feed
sasmaverick
Obsidian | Level 7
I have the following dataset:
X Y
1 70
1 .
1 .
1 .
1 80
1 .
1 .

I want to assign the last non missing value to the missing observations. Expected output as follows
X Y
1 70
1 70
1 70
1 70
1 80
1 80
1 80

Please help. I tried do end loop but to no use.

4 REPLIES 4
sasmaverick
Obsidian | Level 7
Adding to the above requirment, I may also need to pick last non missing in a BY group. That is, I don't need to assign 80 if X=2.
paulkaefer
Lapis Lazuli | Level 10

Remove the rename and drop statements if you want the new variable to be in its own column.

 

data temp;
   input X Y;
   datalines;
1 70
1 .
1 .
1 .
1 80
1 .
1 .
;

data temp2;
    set temp;
    retain last_non_missing;
    
    if (not missing(Y)) then
        last_non_missing = Y;

    rename last_non_missing=Y;
    drop Y;
run;

paulkaefer
Lapis Lazuli | Level 10

with your updated requirement, is this what you want? note that the Y value when X is 3 will be .

 

data temp;
   input X Y;
   datalines;
1 70
1 .
1 .
1 .
1 80
1 .
1 .
2 60
2 .
3 .
;

data temp2;
    set temp;
    retain last_non_missing;
    
    if (first.x) then
        last_non_missing = .;

    if (not missing(Y)) then
        last_non_missing = Y;

    by x;
    rename last_non_missing=Y;
    drop Y;
run;
data_null__
Jade | Level 19

This is a good place to apply the UPDATE trick it handles BY group automatically.

 

data XY;
   input X Y @@;
   cards;
1 70 1 . 1 . 1 .
1 80 1 . 1 . 
2 60 2 . 3 .
;;;;
   run;
proc print;
   run;
data LOCF;
   update XY(obs=0) XY;
   by X;
   output;
   run;
proc print;
   run;

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 4 replies
  • 3168 views
  • 0 likes
  • 3 in conversation