BookmarkSubscribeRSS Feed
Bycar81
Calcite | Level 5

Dear all,

I'm principiant in managing consequential values in a dataset and I'd like to kindly ask your support to solve my problem.
I have data variable with positives and negatives in a by group Id for which I generated the cumulative sum, using retain function.

Now I need to manage this sum in the way it does't fall down negative for every row in the group id.
If it happens, the goal would be to set that value of the variable to zero and ricalculate the cumulative sum (a sort of excluding of value when it makes the cum sum negative). And then going ahead to the next row checking any other negative on the "new" cumulative sum, until the end of group id.

 

Attached an example.

Var1 and var_cum are what I have, var2 and var_cum2 are the goal, myvar2 and myvar_cum2 are the result applying the code below.

  

 

data example;

do _n_=1 by 1 until(last.id);

set ppp;
by id;

   if var_sum>=0 then do; 
      var2=var; 
      var_cum2=var_cum;output; 
   end;
   else do;
         var2=0;
         var_cum2=-var+var_cum;
   output;
   end;

end;

run;

Clearly the code below doesn't reach the goal and I know It's just what I told sas to do. It would take a step by step check, I tried a series of tests but I'm at standstill Smiley Sad

I'm sure there's one (and simpler) way to do that, maybe without supporting variables or managing it in generating cum sum with some loops and/or particular conditions.

 

I really appreciate your support

Very thanks in advance

 

1 REPLY 1
s_lassen
Meteorite | Level 14

Please supply your data as a datastep, like this (also do it for the data you want as output):

data ppp;
  input id var;
cards;
1 100
1 500
1 -300
1 -500
1 -200
1 100
1 -800
1 -200
2 500
2 -700
2 -200
2 500
;run;

  I think that what you want can be accomplished like this:

data want;
  set ppp;
  by id;
  if first.id then
    var_cum=var;
  else var_cum+var;
  if var_cum<0 then do;
    var2=0;
    var_cum=var_cum-var;
    end;
  else
    var2=var;
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
  • 1 reply
  • 661 views
  • 0 likes
  • 2 in conversation