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;
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 lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.