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;
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);