R Programming/Control Structures

Conditional execution

 * Help for programming :

if accepts a unidimensional condition.

The unidimensional condition may be one of TRUE or FALSE, T or F, 1 or 0 or a statement using the truth operators:
 * x == y "x is equal to y"
 * <tt>x != y</tt> "x is not equal to y"
 * <tt>x > y</tt> "x is greater than y"
 * <tt>x < y</tt> "x is less than y"
 * <tt>x <= y</tt> "x is less than or equal to y"
 * <tt>x >= y</tt> "x is greater than or equal to y"

And may combine these using the <tt>&</tt> or <tt>&&</tt> operators for AND. <tt>|</tt> or <tt>||</tt> are the operators for OR.

The <tt>ifelse</tt> command takes as first argument the condition, as second argument the treatment if the condition is true and as third argument the treatment if the condition is false. In that case, the condition can be a vector. For instance we generate a sequence from 1 to 10 and we want to display values which are lower than 5 and greater than 8.

Sets
R has some very useful handlers for sets to select a subset of a vector:

to exclude a subset of a vector:

Implicit loops
R has support for implicit loops, which is called vectorization. This is built-in to many functions and standard operators. for example, the  operator can add two arrays of numbers without the need for an explicit loop.

Implicit Loops are generally slow, and it is better to avoid them when it is possible.
 * <tt>apply</tt> can apply a function to elements of a matrix or an array. This may be the rows of a matrix (1) or the columns (2).
 * <tt>lapply</tt> applies a function to each column of a dataframe and returns a list.
 * <tt>sapply</tt> is similar but the output is simplified. It may be a vector or a matrix depending on the function.
 * <tt>tapply</tt> applies the function for each level of a factor.


 * See also <tt>aggregate</tt> which is similar to <tt>tapply</tt> but is applied to a dataframe instead of a vector.

Explicit loops
R provides three ways to write loops: for, repeat and while. The <tt>for</tt> statement is excessively simple. You simply have to define index (here k) and a vector (in the example below the vector is 1:5) and you specify the action you want between braces. When it is not possible to use the for statement, you can also use break or while by specifying a breaking rules. One should be careful with this kind of loops since if the breaking rules is misspecified the loop will never end. In the two examples below the standard normal distribution is drawn in as long as the value is lower than 1. The cat function is used to display the present value on screen.

The  statement can be used to discontinue one particular cycle and skip to the “next”.

Iterators

 * Loops in R are generally slow. <tt>iterators</tt> may be more efficient than loops. See this entry in the Revolution Computing Blogs