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 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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