Hi I have created a dataset with some sample values like below;
data a;
input x @@;
datalines;
1 2 0 0 3 4 5 0 0 0 6
;
Now i need to create another variable x1 where the non zero value of x should retain instead of 0's. The output i am looking for is
1 2 2 2 3 4 5 5 5 5 6.
I tried using lag function but i am not able to retain it if it has more than one 0 successively. Any help?
You've already found the right word: retain.
The code should look like this:
data want;
set have;
retain _x 0;
if x ne 0
then _x = x; * this will always keep the last non-zero value;
else x = _x; * and this overrides the zeroes;
drop _x;
run;
If you need to do it for groups, the init of _x to 0 has to be done at first.group instead of in the retain statement.
You've already found the right word: retain.
The code should look like this:
data want;
set have;
retain _x 0;
if x ne 0
then _x = x; * this will always keep the last non-zero value;
else x = _x; * and this overrides the zeroes;
drop _x;
run;
If you need to do it for groups, the init of _x to 0 has to be done at first.group instead of in the retain statement.
data a;
input x @@;
datalines;
1 2 0 0 3 4 5 0 0 0 6
;
data want;
set a;
_iorc_=ifn( x=0 and lag(x) ne 0 ,lag(x),_iorc_);
if x=0 then x=_iorc_;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.