DATA Step, Macro, Functions and more

How to inherit the value from previous value

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 12
Accepted Solution

How to inherit the value from previous value

Hello,

I wonder if someone could help me? I try to make a table which inherits the group information from previous value. Thank you.

Input:

groupid
group11
 2
 3
group24
 5
group36

 

Ouput:

groupid
group11
group22
group33
group24
group35
group36

Accepted Solutions
Solution
‎05-02-2017 11:21 AM
PROC Star
Posts: 7,489

Re: How to inherit the value from previous value

Posted in reply to lionking19063

Either I don't understand or your example wasn't right. Are you trying to do the following:

 

data have;
  infile cards dlm=',' truncover;
  input group $ id;
  cards;
group1,1
 ,2
 ,3
group2,4
 ,5
group3,6
;

proc sort data=have;
  by descending id;
run;

data want (drop=hold);
  set have;
  retain hold;
  if not missing(group) then hold=group;
  else group=hold;
run;

Art, CEO, AnalystFinder.com

 

View solution in original post


All Replies
Solution
‎05-02-2017 11:21 AM
PROC Star
Posts: 7,489

Re: How to inherit the value from previous value

Posted in reply to lionking19063

Either I don't understand or your example wasn't right. Are you trying to do the following:

 

data have;
  infile cards dlm=',' truncover;
  input group $ id;
  cards;
group1,1
 ,2
 ,3
group2,4
 ,5
group3,6
;

proc sort data=have;
  by descending id;
run;

data want (drop=hold);
  set have;
  retain hold;
  if not missing(group) then hold=group;
  else group=hold;
run;

Art, CEO, AnalystFinder.com

 

Occasional Contributor
Posts: 12

Re: How to inherit the value from previous value

Thank you so much. It worked.

Super User
Super User
Posts: 7,074

Re: How to inherit the value from previous value

[ Edited ]
Posted in reply to lionking19063

You should just be able to use a retained variable.

data want ;
  set have;
  hold = coalescec(group,hold);
  group = coalescec(group,hold);
  retain hold;
  drop hold;
run;

Unfortunately SAS sees the first reference to HOLD as being the reference inside the function call instead of the result of assignment statement and defaults HOLD to numeric.  So you need to add a LENGTH statement to define HOLD.

 

Or you could use this trick to make a copy of GROUP with the name of HOLD. That way you do not need to know the length of GROUP in advance.  It will also mark the variable as retained since it is coming from a dataset, so the RETAIN statement is not needed.

 

data want ;
   set have have (obs=0 rename=(group=hold));
   hold = coalescec(group,hold);
   group = coalescec(group,hold);
   drop hold;
run;

 

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 118 views
  • 0 likes
  • 3 in conversation