Hi,
A sample while loop:
data test;
x = 1.5;
i=1;
do while (i < 5);
i = i + x;
output;
end;
run;
The result would have 3 observations with i = 5.5 as the 3rd or last observation.
My question is, how do I make sure that my output is excluding the value N in the DO WHILE condition.
do while (i < n)
So, the above would only have 2 observations, with the i = 5.5 observation been excluded.
I am asking this as in general, because it seems it'll always include the last observation where it doesn't meet the condition to break the loop.
Your code does a test using the value in I but then you first increase I before writing it to the output.
This means the value for I you see in your output is not the value of I that had been used for the current iteration of your test but is the value that will get used in the next iteration.
If you write your data to output before you change the value of I then you see what value has actually been used as condition in your do while loop.
data test;
x = 1.5;
i=1;
do while (i < 5);
output;
i = i + x;
end;
run;
proc print data=test;
run;
Three rows selected looks right to me. If you only want two then change your selection.
Your code does a test using the value in I but then you first increase I before writing it to the output.
This means the value for I you see in your output is not the value of I that had been used for the current iteration of your test but is the value that will get used in the next iteration.
If you write your data to output before you change the value of I then you see what value has actually been used as condition in your do while loop.
data test;
x = 1.5;
i=1;
do while (i < 5);
output;
i = i + x;
end;
run;
proc print data=test;
run;
Three rows selected looks right to me. If you only want two then change your selection.
data test;
x = 1.5;
i = 1 + x;
do while (i < 5);
output;
i = i + x;
end;
run;
data test;
x = 1.5;
i=1;
do while (1);
i = i + x;
if i >= 5 then leave;
output;
end;
run;
Why increment the loop counter yourself?
data test;
x = 1.5;
do i=1 to 5 by X;
output;
end;
run;
@Tom That would include the upper boundary. What if this upper boundary would be 5.5?
@Patrick wrote:
@Tom That would include the upper boundary. What if this upper boundary would be 5.5?
Adjust the upper bound as appropriate for whatever you want.
If you want to exclude the upper bound then do something like:
do index=lowerbound to upperbound-delta by step;
Or you can always also add the WHILE () condition.
do index=lowerbound to upperbound by step while (index<upperbound);
do index=lowebound by step while (index<upperbound);
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.