DATA Step, Macro, Functions and more

Retain value based on another variable

Reply
Frequent Contributor
Frequent Contributor
Posts: 103

Retain value based on another variable

Have: 

IDDayR
1  
1  
1Day 1 
1Day 2run 0
1  
1  
1  
1  
1Day1run 1
1  
1Day2run2
1  
1  

 

Want:

IDDayR
1  
1  
1Day 1 
1Day 2run 0
1 run 0
1 run 0
1 run 0
1 run 0
1Day1run 1
1 run 1
1Day2run2
1 run2
1 run2

 

I want to retain the value of R based on the value of Day (R value carried forward until the next Day

). Any help to achieve this using the retain function?

 

Thanks,

Respected Advisor
Posts: 3,799

Re: Retain value based on another variable

This is pretty standard LOCF.

 

data run;
   infile cards missover;
   input ID Day &$ run &$;
   cards;
1 
1 
1 Day 1
1 Day 2  run 0
1 
1 
1 
1 
1 Day1  run 1
1 
1 Day2  run 2
1 
1 
;;;;
   run;
proc print;
   run;
data run;
   if 0 then set run;
   update run(keep=id obs=0) run(keep=id run);
   by id;
   set run(keep=day);
   output;
   run;
proc print;
   run; 

Capture.PNG

Frequent Contributor
Frequent Contributor
Posts: 103

Re: Retain value based on another variable

Posted in reply to data_null__

Thanks @data_null__

Frequent Contributor
Frequent Contributor
Posts: 103

Re: Retain value based on another variable

@data_null__. It works but difficult to understand to modify to copy the remaining variables as such in the dataset. My original dataset contains 50 variables and those be copied as such. Any pointers? Thanks

Respected Advisor
Posts: 3,799

Re: Retain value based on another variable

[ Edited ]

ari wrote:

@data_null__. It works but difficult to understand to modify to copy the remaining variables as such in the dataset. My original dataset contains 50 variables and those be copied as such. Any pointers? Thanks


 

Did you do any reading in the SAS online documentation about the statements used in the program?

 

change

 

set run(keep=day);

to

set run(drop=id run);

All variables in RUN except ID and RUN are added but their values are not carried forward.

 

The SET statement is to bring in all the variables that you do not want have values carried forward.

Ask a Question
Discussion stats
  • 4 replies
  • 203 views
  • 1 like
  • 2 in conversation