Reputation: 167
I am very new to sas so I am still learning retain statement; I have a datasets with ID and total spending; I want to get the cumulative spending of each customer by using the retain statement; my codes were following;
data ex03.try1; set ex03.sorted;
by ID;
if first.ID then do;
retain total 0;
total = total+amount; end;
else do; total=total+amount; end;
run;
However, my codes do not really set the initial value for total to be 0 for each new ID; would anyone please help me to understand where I did wrong please;
Appreciated it;
Thanks again;
Upvotes: 0
Views: 647
Reputation: 51581
The RETAIN statement is evaluated during compilation of the data step. Where you place it doesn't really matter much, it will have the same effect. In particular placing it inside of a conditional does nothing. The RETAIN statement tells SAS that it is not to set the value to missing when the next iteration of the data step starts. The optional initial value on the retain statement will set the value before the first iteration of the data step.
To change the value for each new ID value you need to use an actual assignment statement that will actually do something during the running of the data step.
You can use a SUM statement and make your code shorter. Using the SUM statement implies that the variable is retained and initialized to zero.
data want;
set have;
by id;
if first.id then total=0;
total+amount;
run;
Note that the SUM statement will also handle missing values of the AMOUNT variable. It is really the equivalent of:
retain total 0;
total=sum(total,amount);
Upvotes: 2
Reputation: 167
I have gotten it worked by putting retain total 0 outside of the if then else statement like
by ID;
retain total 0;
if first.ID then do;
total=0;
total=total+amount;
else do;
total=total+amount;
run;
But still, could anyone explain to me why my pervious codes didn't work. I was thinking if it is a new ID, then set total to be 0 otherwise just keep adding the value. I guess I must be wrong about it
Thanks again;
Upvotes: 0