BookmarkSubscribeRSS Feed
Ronein
Meteorite | Level 14

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

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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