| Control {base} | R Documentation |
Control Flow
Description
These are the basic control-flow constructs of theR language. Theyfunction in much the same way as control statements in any Algol-likelanguage. They are allreserved words.
Usage
if(cond) exprif(cond) cons.expr else alt.exprfor(var in seq) exprwhile(cond) exprrepeat exprbreaknextx %||% yArguments
cond | A length-one logical vector that is not |
var | A syntactical name for a variable. |
seq | An expression evaluating to a vector (including a list andanexpression) or to apairlist or |
expr,cons.expr,alt.expr,x,y | Anexpression in a formal sense. This is either asimple expression or a so-calledcompound expression, usuallyof the form |
Details
break breaks out of afor,while orrepeatloop; control is transferred to the first statement outside theinner-most loop.next halts the processing of the currentiteration and advances the looping index. Bothbreak andnext apply only to the innermost of nested loops.
Note that it is a common mistake to forget to put braces ({ .. })around your statements, e.g., afterif(..) orfor(....).In particular, you should not have a newline between} andelse to avoid a syntax error in entering aif ... elseconstruct at the keyboard or viasource.For that reason, one (somewhat extreme) attitude of defensive programmingis to always use braces, e.g., forif clauses.
Theseq in afor loop is evaluated at the start ofthe loop; changing it subsequently does not affect the loop. Ifseq has length zero the body of the loop is skipped. Otherwise thevariablevar is assigned in turn the value of each element ofseq. You can assign tovar within the body of the loop,but this will not affect the next iteration. When the loop terminates,var remains as a variable containing its latest value. Theseq is implicitly unclassed. For classed objects, one can useas.list to prepare a list to iterate over orseq_along to get an index vector and then explicitly extractindividual elements (see alsolapply).
The null coalescing operator%||% is a simple 1-line function:x %||% y is an idiomatic way to call
if (is.null(x)) y else x # or equivalently, of course, if(!is.null(x)) x else y
Inspired by Ruby, it was first proposed by Hadley Wickham.
Value
if returns the value of the expression evaluated, orNULL invisibly if none was (which may happen if there is noelse).
for,while andrepeat returnNULL invisibly.for setsvar to the last used element ofseq,or toNULL if it was of length zero.
break andnext do not return a value as they transfercontrol within the loop.
References
Becker R. A., Chambers J. M., Wilks A. R. (1988).The New S Language.Chapman and Hall/CRC, London.ISBN 053409192X.
See Also
Syntax for the basicR syntax and operators,Paren for parentheses and braces.
ifelse,switch for other ways to control flow.
Examples
for(i in 1:5) print(1:i)for(n in c(2,5,10,20,50)) { x <- stats::rnorm(n) cat(n, ": ", sum(x^2), "\n", sep = "")}f <- factor(sample(letters[1:5], 10, replace = TRUE))for(i in unique(f)) print(i)res <- {}res %||% "alternative result"x <- head(x) %||% stop("parsed, but *not* evaluated..")res <- if(sum(x) > 7.5) mean(x) # may be NULLres %||% "sum(x) <= 7.5"