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

## retain statement

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
Tourmaline | Level 20

## Re: retain statement

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
3 REPLIES 3
Tourmaline | Level 20

## Re: retain statement

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
Fluorite | Level 6

## Re: retain statement

Thank you, ChrisNZ
Tourmaline | Level 20

## Re: retain statement

``````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;``````
Discussion stats
• 3 replies
• 1016 views
• 3 likes
• 3 in conversation