BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
cmemtsa
Quartz | Level 8
data T;
input ID L M EXP;
Datalines;
1 1 100 10
1 2 100 20
1 2 100 20
1 3 100 30
2 1 50 10
2 1 50 20
2 2 50 60
;

Hi, based on this dataset I want to create a new dataset with an extra column (WANTED) which includes the following steps:

1. All calculations are per group ID

2. For each first ID occurrence, the value WANTED is equal to the value in Col EXP

3. For the second row and so on, the formula is IF L=1 then =EXP Else if (cumulative sum of previous values WANTED<MV) then MV-LAG(EXP) ELSE 0  

 

Finally the WANTED column should have the following values

10

90

0

0

10

20

30

 

Thank you in advance for your help.

 

1 ACCEPTED SOLUTION
4 REPLIES 4
Kurt_Bremser
Super User

Then I think this should do it:

data want;
set t;
by id;
l_exp = lag(exp); /* never call LAG() conditionally */
if first.id
then do;
  wanted = exp;
  sum_wanted = exp;
end;
else do;
  if l = 1
  then wanted = exp;
  else if sum_wanted < m
  then wanted = m - l_exp;
  else wanted = 0;
  sum_wanted + wanted; /* increment statement causes automatic retain */
end;
drop sum_wanted l_exp;
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!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 4 replies
  • 611 views
  • 2 likes
  • 2 in conversation