[R] labeled break statements in R?
Gabor Grothendieck
ggrothendieck at myway.com
Thu Aug 19 14:47:36 CEST 2004
Gabor Grothendieck <ggrothendieck <at> myway.com> writes:
> Roger Levy <rog <at> stanford.edu> writes:
> : Are there labeled break statements in R? i.e., something along the
> : lines of
> :
> : TOPLOOP: for(i in 1:m) {
> : for(j in 1:n) {
> : ...
> : if(condition) {
> : break TOPLOOP
> : }
> : }
> : }
>
> Assuming that your labelled break is supposed to break out of
> both loops, unlike an ordinary break that just breaks out of
> the inner loop, this is how it would be done:
>
> a <- matrix(0, nr=3, nc=3)
> local({
> for(i in 1:3)
> for(j in 1:3)
> if (i+j>4) return() else a[i,j] <<- i+j
> })
> a
>
> Be aware that assigning variables within the local will assign
> local copies unless you use <<-, assign(..., ..., parent.frame())
> or eval.parent(...).
An improvement over the above is to use evalq as this does not set
up a local environment, thereby avoiding the problems cited in
the last sentence:
a <- matrix(0, nr=3, nc=3)
evalq({
for(i in 1:3)
for(j in 1:3)
if (i+j>4) return() else a[i,j] <- i+j
})
a
Note that we were able to replace the <<- with <-.
More information about the R-help
mailing list