DATA Step, Macro, Functions and more

do loop, retain and lag?

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 104
Accepted Solution

do loop, retain and lag?

Dear SAS community, 

 

I have a very simple calculation problem that I can't quite seem to solve using a combination of do loops, lag functions and a retain statement.  In general, I would like to calculate a new denominator based on values from a previous numerator observation.    For example on Day 2 - the denom = 499 because on Day 1 denom of 500 - numer of 1 = 499.  For day 3, the denom = 497 because the day 2 denom of 499 - day 2 numer of 2 = 497. Below is what I would like my final dataset to look like. Thoughts?

 

Thank you!

 

data want;

input day numer denom;

datalines;;

1 1 500

2 2 499

3 1 497

4 1 496

5 2 495

;;

 


Accepted Solutions
Solution
‎10-03-2016 10:37 AM
Super User
Posts: 17,930

Re: do loop, retain and lag?

It's not clear what you start with. 

Perhaps this will help. 

 

 

 

 

Retain denom2;

 

Y = lag(numer);

if _n_ ne 1 then denom2= denom2 - y;

Else denom2=denom;

View solution in original post


All Replies
Solution
‎10-03-2016 10:37 AM
Super User
Posts: 17,930

Re: do loop, retain and lag?

It's not clear what you start with. 

Perhaps this will help. 

 

 

 

 

Retain denom2;

 

Y = lag(numer);

if _n_ ne 1 then denom2= denom2 - y;

Else denom2=denom;

Frequent Contributor
Posts: 104

Re: do loop, retain and lag?

This is great! Thank you so much!
Super User
Posts: 5,096

Re: do loop, retain and lag?

I would look at it in this way:

 

data want;

set have;

new_denom = 500 - total_numer;

total_numer + numer;

run;

 

Adjustments could be made if you don't want to start at 500 each time.  But the subtraction has to take place first, before recalculating the TOTAL_NUMER.

Frequent Contributor
Posts: 104

Re: do loop, retain and lag?

This also works great! Thank you both for responding so quickly.
☑ This topic is solved.

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

Discussion stats
  • 4 replies
  • 341 views
  • 0 likes
  • 3 in conversation