RFirst Steps in R

Table Of Contents

Previous topic

Basic Operations

Next topic

Data Reading and Writting

This Page

Control Structures

Types

Böhm and Jacopini’s work [1] in 1966, showed that the computer programs can be developed using only three control structures:

1. Sequence Structure: the instructions are executed in the sequential order they have been written, unless the contrary is specified. In R, this behaviour is inherent to the interactive execution (through the R interpreter) and it is also the way in which instructions are executed in a script.

2. Selection Structure: different instructions can be executed depending on a condition. In R this is implemented through:

> if(cond) expr
> if(cond) cons.expr  else  alt.expr

3. Repetition Structure: the execution of a group of instructions can be repeated inside a loop. This can be accomplished by:

> for (name in expr_1) expr_2
> while (condition) expr
> repeat expr

Every algorithm can be resolved using the control structures described above. These structures can be nested so the use of braces “{...}” and proper indentation make the blocks of instructions clearer:

for (x in seq(-3,3)) {
  if (x < 0) {
    print("Caso A:")
    y <- sqrt(-x)
    cat("y=",y,"\n")
  } else {
    print("Caso B:")
    y <- sqrt(x)
    cat("y=",y,"\n")
  }
}

Control Flow: break, next, return

These three commands are used to alter the normal execution of the control structures. From R help:

break: breaks out of a ‘for’, ‘while’ or ‘repeat’ loop (applies only to the innermost loop).

next: halts the processing of the current iteration and advances the looping index (applies only to the innermost loop.)

return: returns a value in a function and exits it.

Footnotes

[1]Böhm C., and Jacopini G,. Flow Diagrams, Turing Machines, and Languages with Only Two Formation Rules, Communications of the ACM, Vol 9., No. 5, 1966, 336–371.