Lets say I have a table called: pg2. savings looking like this:
Obs | Name | Amount |
1 | James | 250 |
2 | Linda | 300 |
3 | Mary | 275 |
4 | Robert | 350 |
data YearSavings; set pg2.savings; *savings = 0; *This will solve the problem of question 1 below.; do Month=1 to 12; Savings+Amount; Savings+(Savings*0.02/12); end; format Savings comma12.2; *Month = Month-1; *Related to question 2; run;I get the following output:
Obs | Name | Amount | Month | Savings |
1 | James | 250 | 13 | 3,032.70 |
2 | Linda | 300 | 13 | 6,733.15 |
3 | Mary | 275 | 13 | 10,205.03 |
4 | Robert | 350 | 13 | 14,656.79 |
*savings = 0; *This will solve the problem of question 1 below.;
*Month = Month-1;Is there any best practices for this?
Hello @SasStatistics,
@SasStatistics wrote:
2. Despite running 12 months in the iterations, it shows up as 13 which is pretty uggly. One solution would be to un-comment the row:*Month = Month-1;Is there any best practices for this?
It is this additional incrementation of the index variable beyond the stop value (here: 12) which causes the loop to stop iterating. Sometimes this can be useful, e.g., because the final value of the index variable shows that the loop did not stop during the last iteration or earlier (example).
There are several reasons why in practice those "ugly" values are rarely an issue (that requires a statement like Month = Month-1):
data ...(drop=i); ... do i=1 to ...; ... end; ... run;
do Month=1 by 1 until(Month=12);
do Month=1 by 1 while(Month<=12);
Hello @SasStatistics,
@SasStatistics wrote:
2. Despite running 12 months in the iterations, it shows up as 13 which is pretty uggly. One solution would be to un-comment the row:*Month = Month-1;Is there any best practices for this?
It is this additional incrementation of the index variable beyond the stop value (here: 12) which causes the loop to stop iterating. Sometimes this can be useful, e.g., because the final value of the index variable shows that the loop did not stop during the last iteration or earlier (example).
There are several reasons why in practice those "ugly" values are rarely an issue (that requires a statement like Month = Month-1):
data ...(drop=i); ... do i=1 to ...; ... end; ... run;
do Month=1 by 1 until(Month=12);
do Month=1 by 1 while(Month<=12);
If you really want to keep MONTH to indicate how many months ahead the calculated amount represents then use a different variable for the loop counter.
months=12 ;
do i=1 to months ;
....
end;
drop i;
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.