Hello
I want to create a new column "Cum_X" that calculate accumulate value of X.
I want to ask if the location of Retain is important?
What is the common location of Retain ?
Data a;
input Id X;
cards;
1 10
2 30
3 20
4 10
5 40
;
Run;
Data wanted1;
SET a;
Retain Cum_X;
IF _n_=1 then Cum_X=X;
Else Cum_X= Cum_X+X;
Run;
Data wanted2;
SET a;
IF _n_=1 then Cum_X=X;
Else Cum_X= Cum_X+X;
Retain Cum_X;
Run;
Data wanted3;
Retain Cum_X;
SET a;
IF _n_=1 then Cum_X=X;
Else Cum_X= Cum_X+X;
Run;
Hello,
The Type of the RETAIN statement is "Declarative".
A RETAIN statement is a declarative statement which is used in building the Program Data Vector (PDV) during the compilation phase of the DATA step.
In your example I would put it right before or right after the SET statement. The difference is in the order of the variables in the output dataset.
See this usage note for more insight:
Usage Note 8395: How to reorder the variables in a SAS® data set
https://support.sas.com/kb/8/395.html
Have a nice day,
Koen
You don't need RETAIN at all, you can use a SUM statement.
data want;
set a;
cum_x+x;
run;
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
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.