Sentry Page Protection
Data Manipulation [17-18]
Assigning initial values with Retain Statement
There are 3 ways to assign initial values with a Retain statement:
- Retain Var1 0
- Retain Var1 .
- Retain Var1
Let's take a look at some examples with the REVENUE data set.
1. Retain Var1 0;
Example
Data Revenue2;
Set Revenue;
Retain Total 0;
Run;
The Retain statement allows you to add an initial value to the variable.
In this example, we assigned the initial value of 0 to the variable Total.
Since the value is retained from one observation to the next, the entire column contains the value of 0.
Let's try another initial value:
Example
Data Revenue3;
Set Revenue;
Retain Total 100;
Run;
The initial value is set as 100.
2. Retain Var1 .
The initial value can also be missing (.).
Let's run the code below:
Example
Data Revenue4;
Set Revenue;
Retain Total .;
Run;
A missing value (dot) is assigned to the entire column.
3. Retain Var1
When no initial value is given in the Retain statement, the initial value is set as missing (dot).
However, the variable is NOT created when no initial value is given.
Example
Data Revenue5;
Set Revenue;
Retain Total;
Run;
Cumulative Summation
When computing cumulative summation, assigning the initial value is not needed.
Example
Data Revenue3;
Set Revenue;
Retain Total;
Total = sum(revenue, total);
Run;
The summation can still be calculated without specifying the initial value.
(Hint: this is a popular SAS Base exam question.)
Exercise
Copy and run the INVENTORY data set from the yellow box below:
Copy and run the INVENTORY data set from the yellow box below:
The INVENTORY data set contains the inventory of a bookshelf from a furniture store.
The initial inventory of the bookshelf is 1500.
Compute the total inventory across all of the stores including the initial inventory.
Need some help?
HINT:
Simply set the initial value as 1500 before performing the summation.
SOLUTION:
Data Inventory2;
Set Inventory;
Retain Total 1500;
Total = sum(QTY, total);
Run;
Fill out my online form.