Dear SAS users,
I have a basic question. Why is i 5.5 upon the following code when the output statement is not given:
data A;
do i = 1 to 5 by 0.5;
y = i**2;
output;
end;
run;
proc print data = A;
run;
data A;
do i = 1 to 5 by 0.5;
y = i**2;
end;
run;
proc print data = A;
run;
@vstorme wrote:
I can see that, but when you do add output as in the first case, i=5 in the last observation
That's because the implicit
i + 0.5;
comes after the execution of the output statement, and no implicit output is done after the do loop finishes.
Do this for reference:
data A;
do i = 1 to 5 by 0.5;
y = i**2;
output;
put i=;
end;
put i=;
run;
Read the manual!
i is incremented at the end of the loop to 5.5, however as that is over the top boundary for the do loop, the do loop then exits. The incremenetor will always (upon complete run) be one iteration count above the upper bound. Its a bit like saying:
set i to lower limit start is i over upper limit, no then do ... increment i by one iteration and return to start
I suppose you mean your last data step. The thing is this: if there is no explicit OUTPUT statement in a data step, SAS puts an implicit output statement at the end of the data step. After the loop has run, I=5.5, and that value is output. But for Y you will get 4.5**2, as that was the last assignment inside the loop.
In code,
do i = 1 to 5 by 0.5;
end;
translates to
i = 1;
do while (i <= 5);
i + 0.5;
end;
I can see that, but when you do add output as in the first case, i=5 in the last observation
@vstorme wrote:
I can see that, but when you do add output as in the first case, i=5 in the last observation
That's because the implicit
i + 0.5;
comes after the execution of the output statement, and no implicit output is done after the do loop finishes.
Do this for reference:
data A;
do i = 1 to 5 by 0.5;
y = i**2;
output;
put i=;
end;
put i=;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.