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
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
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;
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.
Ready to level-up your skills? Choose your own adventure.