BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
new510
Fluorite | Level 6

Hi, 

I have a question regarding retain statement. I have the following dataset:

 

Dataset:

ID   flag  var1     

A    1       x1         

A    0      x2           

B    0       x1          

B    0       x2         

 

Result expecting :

ID   flag  var1      want_var2

A    1       x1          x1

A    0      x2           x1

B    0       x1          x1

B    0       x2         x2

 

 I am trying to retain the value of 'var1' if the flag=1 to the next observation of the same id, and keep the same value of var1 if the flag=0.

 

I am using the  code as below:

 

data xy;

input id $ flag $ z $;

datalines;

A 1 A1

A 0 A2

B 0 B1

B 0 B2

;

run;

 

proc sort data=xy; by id descending flag; run;

 

 

data xyz;

set xy;

by id descending flag;

 

retain xy xy2;

if first.id and flag=1 then do;

xy=Z;

end;

else if first.id and flag=0 then do;

xy=z;

end;

 

run;

 

Thank you in advance. 

 

1 ACCEPTED SOLUTION

Accepted Solutions
ChrisNZ
Tourmaline | Level 20

I think you misunderstand what RETAIN does.

This does what you want:

data WANT; 
  set HAVE;
  LAST_VAR1=lag(VAR1);
  VAR2=ifc(lag(FLAG)=1 & lag(ID)=ID, LAST_VAR1, VAR1);
  drop LAST_VAR1; 
run;

 

ID FLAG VAR1 VAR2
A 1 x1 x1
A 0 x2 x1
B 0 x1 x1
B 0 x2 x2

View solution in original post

3 REPLIES 3
ChrisNZ
Tourmaline | Level 20

I think you misunderstand what RETAIN does.

This does what you want:

data WANT; 
  set HAVE;
  LAST_VAR1=lag(VAR1);
  VAR2=ifc(lag(FLAG)=1 & lag(ID)=ID, LAST_VAR1, VAR1);
  drop LAST_VAR1; 
run;

 

ID FLAG VAR1 VAR2
A 1 x1 x1
A 0 x2 x1
B 0 x1 x1
B 0 x2 x2
new510
Fluorite | Level 6
Thank you, ChrisNZ
novinosrin
Tourmaline | Level 20
data xy;

input id $ flag  var1 $;

datalines;
A    1       x1         
A    0      x2           
B    0       x1          
B    0       x2  
;

run;

data want;
set xy;
by id;
retain want;
if first.id then _flag=0;
_flag+flag;
if flag or _flag=0 then want=var1 ;
drop _:;
run;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 1628 views
  • 3 likes
  • 3 in conversation