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;

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

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
  • 1833 views
  • 3 likes
  • 3 in conversation