Program Flow – Loops

September 4th, 2009

The R programming language has keywords defined to allow the user to defined loops in various ways – as a for, while or repeat statement. These statements can be used to ensure that a section of code is repeated multiple times until a defined condition has been satisfied.

The most common loop structure is the for loop which can be used to specify how many times the code within the loop should be repeated and it makes use of an index variable that can be used as part of the code. As a trivial example, let’s say we want to print the logarithm of the conc variable for the first five observations of the CO2 dataset. We would run the following code:

for (i in 1:5)

to produce this output:

[1] 4.553877
[1] 5.164786
[1] 5.521461
[1] 5.857933
[1] 6.214608

After the for command we state the variable that will be used as the looping indicator then its start and end values. These two parts are separated by the in command as can be seen in the example above. The start and end values usually form a valid S statement that produces a vector of values to be used for the loop. In practice we would need use a loop for this type of calculation as we can use the vectorised calculation features of the S language to do this more efficiently:


An alternative is the while statement that is used to run a section of code until a particular condition is satisfied. The condition is stated at the start of the while loop and the code that follows is usually written within curly brackets. A very simple example might look like:

j = 1
while (j < 5)
j = j + 1

that gives this output:

[1] 1
[1] 2
[1] 3
[1] 4

There would of course be more complicated example such as a numerical procedure that keeps running until a specified tolerance is obtained or the number of iterations exceeds a specified value.

Comments are closed.