From the course: SAS® 9.4 Cert Prep: Part 13 Processing Repetitive Code

Demo: Combining iterative and conditional DO loops - SAS Tutorial

From the course: SAS® 9.4 Cert Prep: Part 13 Processing Repetitive Code

Demo: Combining iterative and conditional DO loops

- [Instructor] Let's look at a program that uses a combination of iterative and conditional DO loops. Let's say we would like a loop to execute until a person's savings exceeds $5,000. Or they reach 12 months. Whichever comes first. Let's try this two different ways. First we'll take a look at this DATA step. DO month equal one to 12 while savings is less than or equal to $5,000. This will test the condition at the top of the loop after month is incremented. Now we could look at it the opposite way. And say, DO month equal one to 12 until savings is greater than $5,000. In that example, the condition will be tested at the end of the loop, before month is incremented. I'll run this program which prints the results of these two DATA steps so we can compare the output side by side. Let's take a look at James first. James is 13 in both examples. Because he never reached $5,000 so the index variable month incremented one beyond the stop value. But remember, even though month is 13, the loop only ran 12 times. And now let's look at the other people. Their savings values match in both tables. However, month is different. The values are greater in the DO while results, because month was incremented before the condition was tested. If you want month to represent an accurate count of the number of iterations for each row, it's best to create a counter variable inside the loop. So let's go back to the program. Rather than depend on the index variable to count month I'm going to create month myself. First I'll change the index variable reference of month to an arbitrary letter such as i. Within the DO loop, I'll add a sum statement month plus one. And remember month will be retained, so I need to ensure that I reset month to zero each time I reach the top of the DATA step loop. So after the set statement I'll use an assignment statement to set month equal to zero. Now that I'll have month to represent the number of iterations of the DO loop, I can drop the index variable i. So I'll add a drop statement. I'll make the same modifications in the second DATA step to compare the results and ensure that they match. Now that I've made those changes let's run both DATA steps and PROC print steps and you'll notice that the two tables are exactly the same. The savings amounts match and month now represents the number of months or iterations it took for each individual to either save $5,000 or reach 12 months, whichever came first.

Contents