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

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

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

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;

 

View solution in original post

6 REPLIES 6
novinosrin
Tourmaline | Level 20
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;
novinosrin
Tourmaline | Level 20
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;
Phamhhm
Fluorite | Level 6

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

 

 

 

novinosrin
Tourmaline | Level 20

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;

 

novinosrin
Tourmaline | Level 20

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;

 

Phamhhm
Fluorite | Level 6

Thank you, problem solved

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
Mastering the WHERE Clause in PROC SQL

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.

Discussion stats
  • 6 replies
  • 730 views
  • 0 likes
  • 2 in conversation