BookmarkSubscribeRSS Feed
Ronein
Onyx | Level 15

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;
2 REPLIES 2
sbxkoenk
SAS Super FREQ

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

 

PaigeMiller
Diamond | Level 26

You don't need RETAIN at all, you can use a SUM statement.

 

data want;
    set a;
    cum_x+x;
run;
--
Paige Miller
How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 781 views
  • 0 likes
  • 3 in conversation