Fluorite | Level 6

## Data Manipulation

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;

1 ACCEPTED SOLUTION

Accepted Solutions
Tourmaline | Level 20

## Re: Data Manipulation

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;
``````

6 REPLIES 6
Tourmaline | Level 20

## Re: Data Manipulation

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

## Re: Data Manipulation

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

## Re: Data Manipulation

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

Tourmaline | Level 20

## Re: Data Manipulation

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;``````

Tourmaline | Level 20

## Re: Data Manipulation

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;
``````

Fluorite | Level 6

## Re: Data Manipulation

Thank you, problem solved

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