What is RETAIN statement in SAS

retain
sas

#1

Hi all,

What is RETAIN statement in SAS? Can anyone provide me the full details on it?

I’m unable to figure it out from various topics available online. Please provide me with full program, which is easy to understand the concept.

Regards,
Armaan.


#2

@Armaan

At the beginning of each iteration of the DATA step, SAS replaces variables values under program data vector with missing values. A RETAIN statement overrides this default values. RETAIN statement tells SAS not to set variables with missing values when going from the current iteration of the DATA step to the next i.e. SAS retains the values.

Syntax
RETAIN Var1 Var2 …Varn;

Example:-

DATA Test;
INPUT X;
DATALINES;
1 
2
3
;
Run;

Now look at below code and output, we want to generate a variable Y which should have cumulative values of X.

Data check;
Set Test;
Y=SUM(Y,X);
Run;

Output:

X         Y
1          1
2          2 
3          3

Above, we have not able to return the cumulative value. Now look at below code with RETAIN statement.

Data check;
Set Test;
Retain Y;
Y=SUM(Y,X);
Run;

Output:

  X         Y
    1          1
    2          3 
    3          6

Above after each iteration value of Y was retained and it has returned the cumulative value of X.

Regards,
Sunil