Generating Data with DO Loops |
Using Conditional Clauses with the Iterative DO
Statement![]() ![]() |
You have seen how the DO WHILE and DO UNTIL statements enable you to
execute statements conditionally and how the iterative DO statement enables
you to execute statements a set number of times, unconditionally.
DO WHILE(expression); DO UNTIL(expression); DO index-variable=start TO stop BY increment; Now let's look at a form of the iterative DO statement that combines features of both conditional and unconditional execution of DO loops. In this DATA step, the DO UNTIL statement determines the number of years it takes (13) for an investment to reach $50,000. Suppose you also want to limit the number of years you invest your capital to 10 years. |
data work.invest; do until(capital>=50000); Year+1; Capital+2000; capital+capital*.10; end; run; |
SAS Data Set Work.Invest
|
You can add the UNTIL or WHILE expression to an iterative DO statement
to further control the number of iterations. This iterative DO statement
enables you to execute the DO loop until Capital is greater
than 50000 or the DO loop executes ten times, whichever occurs first. |
data work.invest(drop=i); do i=1 to 10 until(capital>50000); Year+1; Capital+2000; capital+capital*.10; end; run; |
|
In this case, the DO loop stops executing after ten iterations, and the
value of Capital never reaches 50000. If you increase the amount
added to Capital each year to 4000, the DO loop stops executing
after the eighth iteration when the value of Capital exceeds
50000. |
data work.invest(drop=i); do i=1 to 10 until(capital>50000); Year+1; Capital+4000; capital+capital*.10; end; run; |
|
The UNTIL and WHILE specifications in an iterative DO statement function similarly to the DO UNTIL and DO WHILE statements. Both statements require a valid SAS expression enclosed in parentheses. |
UNTIL(expression); DO index-variable=start TO stop BY increment WHILE(expression); |
The UNTIL expression is evaluated at the bottom of the DO loop, so the DO loop always executes at least once. The WHILE expression is evaluated before the execution of the DO loop. So, if the condition is not true, the DO loop never executes. |
![]() ![]() ![]() ![]() ![]() ![]() |
|
![]() |
![]() |
Copyright © 2002 SAS Institute Inc.,
Cary, NC, USA. All rights reserved.