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
Don’t miss the livestream kicking off May 7. It’s free. It’s easy. And it’s the best seat in the house.
Join us virtually with our complimentary SAS Innovate Digital Pass. Watch live or on-demand in multiple languages, with translations available to help you get the most out of every session.
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.