SAS retain statement and existing variables

Viewed 858

I'm trying to understand how the retain statement is supposed to work with existing variables, but still it seems I missing something as I do not get the desired result

In the following example my code aim to create a sort of counter for the value variable

 data new (sortedby=id);
 input id $ value count;
 datalines ;
 d 55 0
 d 66 0
 d 33 0
 run;

 data cc;
 set new;
 by id;
 retain count;
 count+value;
 run;

And I 'm expecting that the count variable will be the result of the cumulation of the value column. However, the result is not achived and the column keep its original 0 values.

I would be interested in understanding why the implict retain statement in the "+" sign is not working in this case.

It is an issue related to the fact that count is an already existing variables?

Bests

3 Answers

From what I learned about retain, I would suggest this solution:

data cc;
if count = . then previous_count = 0; else previous_count = count;
set new;
by id;
drop previous_count;
count = previous_count + value;
run;

A few comments: since count already exists, SAS retains the variable anyway, and you can get the old value before the set is executed.

For the first iteration, count is . and SAS can not add a number to .. I simply fixed that with an if.

As Quentin suggested, adding some put statements really helps to better understand whats going on!

Related