Software tutorial/Programming in R: loops and flow control

From Statistics for Engineering
Jump to: navigation, search
← Extending R with packages (previous step) Tutorial index Next step: Vectors and matrices →


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

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).

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:

# 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 vectors and 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:

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

if-else flow control loops

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

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

← Extending R with packages (previous step) Tutorial index Next step: Vectors and matrices →