[Rd] value of a loop broken by break
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Sun Dec 19 11:20:23 CET 2004
Gabor Grothendieck <ggrothendieck at myway.com> writes:
> Should the 'for' loop in the following example not return 3 rather than 2?
> The Language Manual says that it returns the result of the last evaluated
> statement and that would be the i before the 'break'. 'repeat' and 'while'
> have the same behavior.
>
> R> (for(i in 1:10) if (i==3) { i; break } else i)
> [1] 2
Hmmm... First, let's look at some variants:
> (for(i in 1:10) {pi; if (i==3) { i; break } else 123})
[1] 123
Notice that you're getting neither "2" nor "3.1415926", but the "123"
from the previous iteration. Similarly
> (for(i in 1:10) {pi; if (i==3) { i; break }else 123; 456})
[1] 456
So you are getting the result of the last _completely_ evaluated
statement (the enclosing "{"-statement is not completed either).
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-devel
mailing list