Chapter 11 Control structures of R

(if, else if, ifelse, for, and while; vectorized commands as alternatives)

11.1 Overview

11.1.1 Abstract:

Introducing control structures: if, else if, ifelse, for, and while.

11.1.2 Objectives:

This unit will:

  • introduce the main control structures of R;

11.1.3 Outcomes:

After working through this unit you:

  • can read, analyze and write conditional expressions using if, else, and the ifelse() function;
  • can read, analyze and write for loops using the range operator and the seq_along() function;
  • can construct while loops with a termination condition.

11.1.4 Deliverables:

Time management: Before you begin, estimate how long it will take you to complete this unit. Then, record in your course journal: the number of hours you estimated, the number of hours you worked on the unit, and the amount of time that passed between start and completion of this unit.

Journal: Document your progress in your Course Journal. Some tasks may ask you to include specific items in your journal. Don't overlook these.

Insights: If you find something particularly noteworthy about this unit, make a note in your insights! page.

11.2 Control structures

"Control structures" are parts of the syntax that execute code according to whether some condition is met. Let's look at this with some simple examples:

11.2.1 if and else

# Code pattern
if (<conditional expression evaluates to TRUE>) {
    <execute this block>
} else if (<expression evaluates to TRUE>) {
    <execute this block>
} else {
    <execute this block>
}

11.2.2 conditional expressions

  • anything that evaluates to TRUE or FALSE, or can be coerced to a logical.
  • Obviously the operators:

    • ! - not equals
    • == - equals
    • < - less than
    • \> - greater than
    • <= - less than or equal
    • \>= - greater than or equal
  • but there are also a number of in-built functions that are useful for this purpose:

    • all - are all values in the set TRUE
    • any - are any of the values in the set TRUE
    • exists - does the object exist
    • is.character - is the object of type character
    • is.factor - is the object of type factor
    • is.integer - is the object of type integer
    • is.null - is the object null
    • is.na - is the object NA
    • is.nan - is the object infinite.
    • is.numeric - is the object of type numeric
    • is.unsorted - is the object sorted
    • is.vector - is the object of type vector
  • Simple "if" statement:
    • Rolling a die. If you get a "six", you get to roll again.
x <- sample(1:6, 1)
if (x == 6) {
    x <- c(x, sample(1:6, 1))
}
print(x)
## [1] 5

11.2.3 "if", "else if", and "else"

Here is a popular dice game called high-low.

a <-  sample(1:6, 1)
b <-  sample(1:6, 1)
if (a + b > 7) {
    print("high")
} else if (a + b < 7) {
    print("low")
} else {
    print("seven")
}
## [1] "seven"

We need to talk about conditional expressions that test for more than one condition for a moment, things like: "if this is true OR that is true OR my birthday is a Sunday this year ...". To join logical expressions, R has two distinct sets of operators:

  • | and ||,
  • and & and &&.

| is for "or" and & is for "and". But what about && and ||?

The single operators are "vectorized" whereas the doubled operators short-circuit.

This means if you apply the single operators to a vector, you get a vector of results:

x <- c(1, 3, 5, 7, 11, 13, 17)
x > 3 &  x < 17 # FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE: all comparisons
## [1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
x [x > 3 &  x < 17]  #  5  7 11 13
## [1]  5  7 11 13

whereas this stop at the first FALSE

x > 3 && x < 17 # FALSE:
## [1] FALSE

The vectorized version is usually what you want, e.g. for subsetting, as above. But it is usually not the right way in control structures: there, you usually want never to evaluate unnecessary expressions. Chained "OR" expressions can be aborted after the first TRUE is encountered, and chained "AND" expressions can be aborted after the first FALSE. Which is what the double operators do.

no error: length test is TRUE so is.na() never gets evaluated

x <- numeric()

if (length(x) == 0 || is.na(x)) { print("zero") }  # .
## [1] "zero"

whereas this throws an error, because is.na() is evaluated even though x has length zero.

if (length(x) == 0 |  is.na(x)) { print("zero") }  

Bottom line: always use || and && in control structures.

11.2.4 ifelse

The ifelse() function deserves special mention: its arguments work like an if / else construct ...

ifelse(5 > 7, TRUE, FALSE)

ifelse(runif(1) > 0.5, "pickles", "cucumbers")
## [1] "pickles"

i.e. ifelse(, , )

But the cool thing about ifelse() is that it's vectorized! You can apply it to a whole vector of conditions at once:

set.seed(27);        runif(10)
##  [1] 0.971750231 0.083757509 0.873869923 0.329231364 0.222275513 0.401648218
##  [7] 0.072498519 0.002450234 0.137093998 0.191909064
set.seed(27);        runif(10) > 0.2
##  [1]  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
set.seed(27); ifelse(runif(10) > 0.2, "caution", " to the wind")
##  [1] "caution"      " to the wind" "caution"      "caution"      "caution"     
##  [6] "caution"      " to the wind" " to the wind" " to the wind" " to the wind"
set.seed(NULL)

11.2.5 for

"for" loops are the workhorse of innumerable R scripts. They are controlled by a sequence, and a variable. The body of the loop is executed once for each element in the sequence. Most often, the sequence is a sequence of integers, created with the colon - the range operator. The pattern is:

for ( in ) { }

# simple for loop
for (i in 1:10) {
    print(c(i, i^2, i^3))
}
## [1] 1 1 1
## [1] 2 4 8
## [1]  3  9 27
## [1]  4 16 64
## [1]   5  25 125
## [1]   6  36 216
## [1]   7  49 343
## [1]   8  64 512
## [1]   9  81 729
## [1]   10  100 1000

Let's stay with the high-low game for a moment:

  • What are the odds of winning?
  • Let's simulate some runs with a "for" loop.
N <- 25000
outcomes <- character(N)  # initialize an empty vector
for (i in 1:N) {          # repeat, assign each element of 1:N to
                          # the variable "i" in turn
    a <-  sample(1:6, 1)
    b <-  sample(1:6, 1)
    if (a + b > 7) {
        outcomes[i] <- "high"
    } else if  (a + b < 7) {
        outcomes[i] <- "low"
    } else {
        outcomes[i] <- "seven"
    }
}
head(outcomes, 36)
##  [1] "high"  "high"  "high"  "high"  "low"   "low"   "high"  "low"   "low"  
## [10] "high"  "high"  "high"  "high"  "high"  "high"  "seven" "low"   "seven"
## [19] "high"  "seven" "high"  "low"   "high"  "high"  "high"  "seven" "high" 
## [28] "high"  "high"  "low"   "high"  "low"   "seven" "high"  "low"   "high"
table(outcomes)  # the table() function tabulates the elements
## outcomes
##  high   low seven 
## 10430 10458  4112
                 # of a vector

round((36 * table(outcomes))/N) # Can you explain this expression?

Note that there is nothing special about the expression for (i in 1:N) { ... . Any expression that generates a sequence of items will do; I write a lot of code like for (fileName in dir()) { ... or for (gene in data$name) {... , or for (column in colnames(expressionTable)) {... etc.

Loops in R can be slow if you are not careful how you write them. The reason is usually related to dynamically managing memory. If you can, you should always pre-define objects of sufficient size to hold your results. Even better, use a vectorized approach.

11.2.6 Compare excution times: one million square roots from a vector of random numbers ...

Version 1: Naive for-loop: grow result object as required

N <- 1000000                 # Set N to a large number
x <- runif(N)                # get N uniformily distributed random numbers
y <- numeric()               # create a variable to assign to
startTime <- Sys.time()      # save start time
for (i in 1:N) {             # loop N-times
  y[i] <- sqrt(x[i])         # calculate one square root, grow y to store it
}
Sys.time() - startTime       # time it took
## Time difference of 0.6640909 secs
rm(x)                        # clean up
rm(y)

Version 2: Define result object to be large enough

N <- 1000000                 # Set N to a large number
x <- runif(N)                # get N uniformily distributed random numbers
y <- numeric(N)              # create a variable with N slots
startTime <- Sys.time()      # save start time
for (i in 1:N) {             # loop N-times
  y[i] <- sqrt(x[i])         # calculate one square root, store in Y
}
Sys.time() - startTime       # time it took
## Time difference of 0.294723 secs
rm(x)                        # clean up
rm(y)

Version 3: vectorized

N <- 1000000                 # Set N to a large number
x <- runif(N)                # get N uniformily distributed random numbers
startTime <- Sys.time()      # save start time
y <- sqrt(x)                 # sqrt() is vectorized!
Sys.time() - startTime       # time it took
## Time difference of 0.009957075 secs
rm(x)                        # clean up
rm(y)

The tiny change of pre-allocating memory for the result object y, rather than dynamically growing the vector has made a huge difference. But using the vectorized version of the sqrt() function directly is the fastest approach.

11.2.7 seq_along() vs. range

Consider the following carefully:

Assume we write a loop to iterate over vectors of variable length for example going from e to pi with a given number of elements:

( v5 <- seq(exp(1), pi, length.out = 5) )
## [1] 2.718282 2.824110 2.929937 3.035765 3.141593
( v2 <- seq(exp(1), pi, length.out = 2) )
## [1] 2.718282 3.141593
( v1 <- seq(exp(1), pi, length.out = 1) )
## [1] 2.718282
( v0 <- seq(exp(1), pi, length.out = 0) )
## integer(0)

The idiom we will probably find most commonly for this task is uses the range operator ":"

1:length(v5)
## [1] 1 2 3 4 5
1:length(v2)
## [1] 1 2
for (i in 1:length(v5)) {
  print(v5[i])
}
## [1] 2.718282
## [1] 2.82411
## [1] 2.929937
## [1] 3.035765
## [1] 3.141593
for (i in 1:length(v2)) {
  print(v2[i])
}
## [1] 2.718282
## [1] 3.141593
for (i in 1:length(v1)) {
  print(v1[i])
}
## [1] 2.718282
for (i in 1:length(v0)) {
  print(v0[i])
}
## [1] NA
## integer(0)

The problem with the last iteration is: we probably didn't want to execute the loop if the vector has length 0. But since 1:length(v0) is the same as 1:0, we get an erroneous execution.

This is why we should always use the following idiom instead, when iterating over a vector: the function seq_along().

seq_along() builds a vector of indices over its argument.

seq_along(v5)
## [1] 1 2 3 4 5
seq_along(v2)
## [1] 1 2
seq_along(v1)
## [1] 1
seq_along(v0)
## integer(0)
for (i in seq_along(v5)) {
  print(v5[i])
}
## [1] 2.718282
## [1] 2.82411
## [1] 2.929937
## [1] 3.035765
## [1] 3.141593
for (i in seq_along(v2)) {
  print(v2[i])
}
## [1] 2.718282
## [1] 3.141593
for (i in seq_along(v1)) {
  print(v1[i])
}
## [1] 2.718282
for (i in seq_along(v0)) {
  print(v0[i])
}

Now we get the expected behaviour: no output if the vector is empty.

11.2.8 loops vs. vectorized expressions

If you can achieve your result with an R vector expression, it will be faster than using a loop. But sometimes you need to do things explicitly, for example if you need to access intermediate results.

Here is an example to play some more with loops: a password generator.

Passwords are a pain. We need them everywhere, they are frustrating to type, to remember and since the cracking programs are getting smarter they become more and more likely to be broken.

Here is a simple password generator that creates random strings with consonant/vowel alterations. These are melodic and easy to memorize, but actually as strong as an 8-character, fully random password that uses all characters of the keyboard such as "!He.%2jJ" or "#hb,B2X^" (which is pretty much unmemorizable).

The former is taken from 20^7 X 7^7 10^15 possibilities, the latter is from 94^8 ~ 6 X 10^15 possibilities. High-end GPU supported password crackers can test about 109 passwords a second, the passwords generated by this little algorithm would thus take on the order of 10^6 seconds or eleven days to crack16. This is probably good enough to deter a casual attack.

11.3 Task 22

Copy, study and run the below code

# Suggest memorizable passwords
# Below we use the functions:
?nchar
?sample
?substr
?paste
?print
 
#define a string of  consonants ...
con <- "bcdfghjklmnpqrstvwxz"
# ... and a string of of vowels
vow <- "aeiouy"
 
for (i in 1:10) {  # ten sample passwords to choose from ...
    pass = rep("", 14)  # make an empty character vector
    for (j in 1:7) {    # seven consonant/vowel pairs to be created ...
        k   <- sample(1:nchar(con), 1)  # pick a random index for consonants ...
        ch  <- substr(con,k,k)          # ... get the corresponding character ...
        idx <- (2*j)-1                  # ... compute the position (index) of where to put the consonant ...
        pass[idx] <- ch                 # ...  and put it in the right spot
 
        # same thing for the vowel, but coded with fewer intermediate assignments
        # of results to variables
        k <- sample(1:nchar(vow), 1)
        pass[(2*j)] <- substr(vow,k,k)
    }
    print( paste(pass, collapse="") )  # collapse the vector in to a string and print
}

Try this a few times.

11.3.1 while

Whereas a for-loop runs for a fixed number of times, a "while" loop runs as long as a condition is true, possibly forever. Here is an example, again our high-low game: this time we simulate what happens when we play it more than once with a strategy that compensates us for losing.

Let's assume we are playing high-low in a casino. You can bet high or low. You get two dollars for one if you win, nothing if you lose. If you bet "high", you lose if we roll "low" or "seven". Thus your chances of winning are 15/36 = 42%. You play the following strategy: start with 33 dollars. Bet one dollar. If you win, good. If you loose, triple your bet. Stop the game when your funds are gone (bad), or if you have more than 100 dollars (good) - i.e. you have tripled the funds you risked. Also stop if you've played more than 100 rounds and start getting bored.

funds <- 33
bet <- 1         # our first bet
 
nPlays <- 0      # this counts how often we've played
MAXPLAYS <- 100
 
set.seed(1234567)
while (funds > 0 && funds < 100 && nPlays < MAXPLAYS) {
 
    bet <- min(bet, funds)  # can't bet more than we have.
    funds <- funds - bet    # place the bet
    a <-  sample(1:6, 1)    # roll the dice
    b <-  sample(1:6, 1)
 
    # we always play "high"
    if (a + b > 7) {        # we win :-)
        result <- "Win!  "
        funds <- funds + (2 * bet)
        bet <- 1            # reset the bet to one dollar
    } else {                # we lose :-(
        result <- "Lose."
        bet <- 3 * bet      # increase the bet to 3 times previous
    }
    print(paste("Round", nPlays, result,
                "Funds now:", funds,
                "Next bet:", bet))
    nPlays <- nPlays + 1
}
## [1] "Round 0 Lose. Funds now: 32 Next bet: 3"
## [1] "Round 1 Win!   Funds now: 35 Next bet: 1"
## [1] "Round 2 Win!   Funds now: 36 Next bet: 1"
## [1] "Round 3 Lose. Funds now: 35 Next bet: 3"
## [1] "Round 4 Lose. Funds now: 32 Next bet: 9"
## [1] "Round 5 Lose. Funds now: 23 Next bet: 27"
## [1] "Round 6 Lose. Funds now: 0 Next bet: 69"
set.seed(NULL)

Now before you get carried away - try this with different seeds and you'll quickly figure out that the odds of beating the game are not all that great...

11.4 Task 23

A rocket ship has to sequence a countdown for the rocket to launch. You are starting the countdown from 3. You want to print the value of variable named txt that outputs:

[1] "3" "2" "1" "0" "Lift Off!" Using what you learned above, write a while loop that gives the output above.

Sample Solution:

start <- 3
txt <- as.character(start)
countdown <- start
while (countdown > 0) {
countdown <- countdown - 1
txt <- c(txt, countdown)
}
txt <- c(txt, "Lift Off!")
txt

11.5 Self-evaluation


  1. That's assuming the worst case in that the attacker needs to know the pattern with which the password is formed, i.e. the number of characters and the alphabet that we chose from. But note that there is an even worse case: if the attacker had access to our code and the seed to our random number generator. If you start the random number generator e.g. with a new seed that is generated from Sys.time(), the possible space of seeds can be devastatingly small. But even if a seed is set explicitly with the set.seed() function, the seed is a 32-bit integer (check this with .Machine$integer.max) and thus can take only a bit more than 4 X 10^9 values, six orders of magnitude less than the 10^15 password complexity we thought we had! It turns out that the code may be a much greater vulnerability than the password itself. Keep that in mind. Keep it secret. Keep it safe.