[R] labeled break statements in R?

Gabor Grothendieck ggrothendieck at myway.com
Thu Aug 19 07:51:10 CEST 2004


Gabor Grothendieck <ggrothendieck <at> myway.com> writes:

: 
: Gabor Grothendieck <ggrothendieck <at> myway.com> writes:
: 
: : 
: : Roger Levy <rog <at> stanford.edu> writes:
: : 
: : : 
: : : Hi,
: : : 
: : : 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(...).
: : 
: : Of course this style is not recommended for R, and as someone else 
: : already mentioned, you should try to vectorize your code eliminating 
: : the loops altogether.  For example, the above could be written 
: : without loops like this:
: : 
: : a <- matrix(0, nr=3, nc=3)
: : rc <- row(a) + col(a)
: : a <- ifelse(rc > 4, a, rc)
: : a
: : 
: Sorry, the ifelse line should have been:
: 
: ifelse( t(matrix(cumsum(rc>4),3,3)), a, rc)

or even simpler:

a <- ifelse( matrix(cumsum(rc>4),3,byrow=T), a, rc)




More information about the R-help mailing list