BookmarkSubscribeRSS Feed
PurushReddy
Fluorite | Level 6
Data ds2;
Input id reading;
Cards;
101 98
101 99
101 .
101 97
101 .
102 95
102 .
102 97
102 .
102 98
;

I want in output above value in null (.)place
3 REPLIES 3
novinosrin
Tourmaline | Level 20
Data ds2;
Input id reading;
Cards;
101 98
101 99
101 .
101 97
101 .
102 95
102 .
102 97
102 .
102 98
;

data want;
 set ds2;
 retain t;
 if not missing(reading) then t=reading;
 else reading=t;
 drop t;
run;
/*or*/
data want;
 update ds2(obs=0) ds2;
 by id;
 output;
run;
Jagadishkatam
Amethyst | Level 16

alternatively

 



Data ds2;
Input id reading;
Cards;
101 98
101 99
101 .
101 97
101 .
102 95
102 .
102 97
102 .
102 98
;

data want;
set ds2(rename=(reading=reading2));
retain reading;
by id;
if first.id then reading=.;
if reading2 ne . then reading=reading2;
run;
Thanks,
Jag
s_lassen
Meteorite | Level 14

Your question is titled "using lag function", but none of the answers given use the LAG function. For good reason, it is important to use the LAG function correctly, else the results become unpredictable.

 

For instance, do NOT try this:

Data want;
  set ds2;
  by id;
  if not first.id and missing(reading) then
    reading=lag(reading); 

In the code shown above, no missing values will be replaced, because the LAG function will only be called when the value of READING is missing (each instance of the LAG function in a data step creates its own little queue, where valued are pushed to the top and pulled from the bottom with each call).

 

And even if you changed your code to take that into account, your code would still have problems if you had two or more missing values in row: as the lagged values were fetched, the new missing value would be queued by LAG, and would be fetched for the next missing value.

 

Instead, use the COALESCE function, very handy in cases like this:

data want;
  set ds2;
  by id;
  if not first.id then
    reading=coalesce(reading,_reading);
  _reading=reading;
  drop _reading;
  retain _reading;
run;

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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
  • 3 replies
  • 429 views
  • 1 like
  • 4 in conversation