Controlling Flow of Evaluation

DESCRIPTION:

Controls looping and branching in S-PLUS expressions.

USAGE:

for(name in values) expr
while(test) expr
repeat expr
break
next

REQUIRED ARGUMENTS:

name
a syntactic name for the looping variable. Valid syntactic names are combinations of letters, numbers, and periods not beginning with a number.
values
a S-PLUS expression returning the elements to be looped over.
test
logical expression of length 1.
expr
any S-PLUS expression (which may be a braced list of expressions}.

VALUE:

The for construct in the language assigns name successively to each element in values, then evaluates expr once each time.

The while construct evaluates test. While it is TRUE (i.e., if the first element of the result coerced to mode logical is TRUE), then expr is evaluated.

The repeat construct evaluates expr repeatedly. Because there is no natural end to such a loop, it must be built into expr, typically through the use of an if...else expression with next and break commands.

The value of the entire loop is the useless value vector("missing",0).

DETAILS:

The next construct tells S-PLUS to terminate the current iteration immediately and begin the next iteration.

The break construct tells S-PLUS to terminate the current loop.

An NA value for the test causes an error.

for loops in S-PLUS are often slow and may use excessive amounts of memory. There are often faster alternative to using for loops, particularly involving vectorization -- operating on whole vectors, matrices, etc. at a time rather than in a loop. If looping cannot be avoided, then it is generally faster to use apply , lapply , sapply , or tapply to do the looping than to use for . Another alternative, useful when memory growth with for becomes excessive, is For . See the S-PLUS Programmer's Manual, in particular the chapters on "Using Less Time and Memory" and "Simulations in S-PLUS".

An error during one iteration of a loop may cause execution to terminate, discarding unsaved results. You may save intermediate results using assign (use immediate=T), or trap errors using try .

SEE ALSO:

, , , , , , , , , .

EXAMPLES:

for(i in 1:10) print(i)
n <- 10
while(n > 0) {
  cat("n is still greater than 0\n")
  n <- n - 1
}

old.cummax <- function(x) {
  # Pure S-PLUS version of cumulative maximum
  if(length(x) > 1) {
    for(i in 2:length(x))
      x[i] <- max(x[i - 1], x[i])
  }
  x
}

bitstring <- function(n) {
  string <- numeric(32)
  i <- 0
  while(n > 0) {
    string[32 - i] <- n %% 2
    n <- n %/% 2
    i <- i + 1
  }
  firstone <- match(1, string)
  string[firstone:32]
}

draw.aces <- function() {
  draws <- 0
  aces.drawn <- rep(F, 4)
  repeat {
    draw <- sample(1:52, 1, replace = T)
    draws <- draws + 1
    if(draw %% 13 != 1)
      next
    aces.drawn[draw %/% 13 + 1] <- T
    if(all(aces.drawn))
      break
  }
  cat("It took", draws, "draws to draw all four of the aces!\n")
}