Generating Data with DO Loops |
Constructing DO
Loops |
DO Loop Execution
Using the form of the DO loop just presented, let's see how the DO loop executes in the DATA step. This example calculates the interest earned each month for a one-year investment. data finance.earnings; Amount=1000; Rate=.075/12; do month=1 to 12; Earned+(amount+earned)*(rate); end; run; This DATA step does not read data from another source. When submitted, it compiles and then executes only once to generate data. During compilation, the program data vector is created for the Finance.Earnings data set. |
When the DATA step executes, the values of Amount and
Rate are assigned. |
Next, the DO loop executes. During each execution of the DO loop, the
value of Earned is calculated and added to its previous value.
On the twelfth execution of the DO loop, the program data vector looks like
this: |
After the twelfth execution of the DO loop, the value of
month is incremented to 13. Because 13 exceeds the stop value
of the iterative DO statement, the DO loop stops executing, and processing
continues to the next DATA step statement. The end of the DATA step is reached,
the values are written to the Finance.Earnings data set,
and in this example, the DATA step ends. Only one observation is written
to the data set. |
SAS Data Set Finance.Earnings
Amount
Rate
month
Earned
1000
0.00625
13
77.6326
Notice that the index variable month is also stored in the
data set. In most cases, the index variable is only needed to process the
DO loop and can be dropped from the data set. |
Copyright © 2002 SAS Institute Inc.,
Cary, NC, USA. All rights reserved.