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.
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 |
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 |
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;
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.
Ready to level-up your skills? Choose your own adventure.