Subsections

12.2 Control flow

R provides the standard control flow constructs common to any general purpose language.


12.2.1 Loops

The general format of the for loop is shown below:

for (symbol in sequence) {
    expressions
}

The expressions are run once for each element in the sequence, with the relevant element of the sequence assigned to the symbol.

The while loop has the following general form:

while (condition) {
    expressions
}

The while loop repeats until the condition is FALSE. The condition is an expression that should produce a single logical value.

12.2.2 Conditional statements

A conditional statement in R has the following form:

if (condition) {
    expressions
}

The condition is an expression that should produce a single logical value.

The curly braces are not necessary, but it is good practice to always include them; if the braces are omitted, only the first complete expression following the condition is treated as the trueBody.

It is also possible to have an else clause.

if (condition) {
    trueExpressions
} else {
    falseExpressions
}

Paul Murrell

Creative Commons License
This document is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.