Control
Control Flow

Description

Functions to control looping and branching in expressions or conditionally evaluation of expressions. Either an if expression or an if-else expression is possible.

Usage

for(name in values) expr
while(test) expr 
repeat expr
break
next
if(test) true.expr
if(test) true.expr else false.expr
e1 || e2
e1 && e2

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 an expression returning the elements to be looped over.
test logical expression of length 1.
expr any expression. (Can be a braced list of expressions.)
test logical expression of length 1.
e1 logical expression of length 1.
e2 logical expression of length 1.

Details

An error during one iteration of a loop can cause execution to terminate, discarding unsaved results. You can save intermediate results using assign (use immediate=T), or you can trap errors using try.
Value
forAssigns name successively to each element in values, then evaluates expr once each time.
whileEvaluates test. While it is TRUE (that is, if the first element of the result coerced to mode logical is TRUE), then expr is evaluated.
repeatEvaluates 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 NULL.
ifEvaluates test. If TRUE (that is, if the first element of the result coerced to mode logical is TRUE), then true.expr is evaluated and returned as the value of the whole expression. Otherwise, the value of the expression is false.expr if present, or an empty value otherwise.
&&Returns TRUE if both of its operands are TRUE (in the same sense as test above). If the left operand is not TRUE, the right operand is not evaluated.
||Returns TRUE if one of its operands is TRUE (in the same sense as test above). If the left operand is TRUE, the right operand is not evaluated.
See Also
assign, apply, lapply, sapply, tapply, For, if, try, Syntax. Logic, ifelse, switch
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 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") }

Package base version 6.0.0-69
Package Index