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: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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