Hi,
Some values of my var X are 0, and i want to replace all of them by the previous value.
X Xnew
1 1
2 2
0 2
4 4
3 3
0 3
7 7
My code does not work:
DATA Tnew;
SET Told;
IF X=0 THEN Xnew=lag(X);
RUN;
thank for your help
Hi @Phamhhm
Forget the lag function, Just retain will do
data have;
input X ;
cards;
1 1
2 2
0 2
4 4
3 3
0 3
0 3
4 4
5 5
0 5
0 5
0 5
;
data want;
set have;
retain t;
if x ne 0 then do;
t=x;
xnew=x;
end;
else xnew=t;
drop t;
run;
data have;
input X ;
cards;
1 1
2 2
0 2
4 4
3 3
0 3
7 7
;
data want;
set have;
x=ifn(x=0,lag(x),x);
run;
data have;
input X ;
cards;
1 1
2 2
0 2
4 4
3 3
0 3
7 7
;
data want;
set have;
xnew=ifn(x=0,lag(x),x);
run;
Thank for your answer, the code works, but i forgot something
X Xnew
1 1
2 2
0 2
4 4
3 3
0 3
0 3
4 4
5 5
0 5
0 5
0 5
some rows have 2 or 3 consecutive zeros
Ok @Phamhhm
Try
data have;
input X ;
cards;
1 1
2 2
0 2
4 4
3 3
0 3
0 3
4 4
5 5
0 5
0 5
0 5
;
data want;
set have;
retain temp;
temp=ifn( x=0 and lag(x) ne 0 ,lag(x),temp);
xnew=ifn( x=0,temp,x);
drop temp;
run;
Hi @Phamhhm
Forget the lag function, Just retain will do
data have;
input X ;
cards;
1 1
2 2
0 2
4 4
3 3
0 3
0 3
4 4
5 5
0 5
0 5
0 5
;
data want;
set have;
retain t;
if x ne 0 then do;
t=x;
xnew=x;
end;
else xnew=t;
drop t;
run;
Thank you, problem solved
April 27 – 30 | Gaylord Texan | Grapevine, Texas
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 save with the early bird rate—just $795!
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.