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

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?

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

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.

View solution in original post

3 REPLIES 3
Kurt_Bremser
Super User

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.

BalajiBollu
Obsidian | Level 7
Thanks KurtBremser. This is working
novinosrin
Tourmaline | Level 20
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: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 2913 views
  • 3 likes
  • 3 in conversation