Software tutorial/Programming in R: loops and flow control

From Statistics for Engineering
< Software tutorial
Revision as of 03:48, 15 January 2013 by Kevin Dunn (talk | contribs) (Created page with "{{Navigation|Book=Software tutorial|previous=Extending R with packages|current=Tutorial index|next=Vectors and matrices}} __NOTOC__ <rst> <rst-options: 'toc' = False/> <rst-o...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
← Extending R with packages (previous step) Tutorial index Next step: Vectors and matrices →


<rst> <rst-options: 'toc' = False/> <rst-options: 'reset-figures' = False/>

R is also a general programming language. This section is a *very* brief introduction to creating ``for`` loops, and ``if-else`` flow control.

.. _r-programming-loops-for-loop:

For loops


A ``for`` loop will repeat a chunk of code a certain number of times. The number of times it will execute is determined by the *looping variable*. In this example we calculate the average of 100 uniformly distributed random numbers, and display that average 4 times (the looping variable is ``1, 2, 3, 4``).

.. code-block:: s

n_loops <- 4 for (i in 1:n_loops) { # 100 uniformly distributed numbers between 1 and 6 x <- as.integer(runif(100, 1, 7)) print(mean(x)) } # Printed output [1] 3.58 [1] 3.67 [1] 3.13 [1] 3.71


The looping variable, called ``i`` in the above example, started at ``1`` and ended at ``n_loops``. But we can use an arbitrary sequence of numbers in a vector to loop on:


.. code-block:: s

# You can put the opening brace for the loop one line # up, if you prefer. Compare to previous example.

for (i in seq(2, 10, 3)){ print(i) } # Printed output [1] 2 [1] 5 [1] 8

# We can create the vector ahead of time idx <- c(2, 5, 7, 3, 1)

# One-line for-loops can be written more compactly # but may become hard to read and debug for (i in idx) print(i)

# Printed output [1] 2 [1] 5 [1] 7 [1] 3 [1] 1

Most often though we want to store the results of our ``for``-loop calculation. You might want to read the section on creating empty :ref:`vectors and matrices <r-vectors-matrices>` first and then come back here.

Returning back to the previous example: let's say we want to store the mean values from the uniform distribution, instead of printing them to the screen:

.. code-block:: s

n_loops <- 10 x.means <- numeric(n_loops) # create a vector of zeros to store the results in for (i in 1:n_loops){ x <- as.integer(runif(100, 1, 7)) # uniformly distributed numbers between 1 and 6 x.means[i] <- mean(x) } x.means

# Printed output [1] 3.21 3.73 3.41 3.61 3.39 3.91 3.60 3.32 3.52 3.49

.. While loops

A ``while`` loop while execute the chunk of code as long as the condition in the loop is true. A ``while`` loop can run an infinite number of times if poorly coded, or may run zero times (intentionally).

if-else flow control loops


Branching your code (controlling its flow) using if-else blocks is given by this syntax in R:

.. code-block:: s

if (...condition 1...){ .... statements .... } elseif(...other condition 2...){ .... other statements .... } elseif(...other condition etc...){ .... more statements .... } else{ .... and yet more statements .... }

</rst>