Flow control and loops

Day 2, A

Michael C Sachs

Flow control

What?

  • Normally the code gets run line by line, in order, top to bottom

  • There are special commands that allow you change that

  • Conditional execution, choose which code to run depending on logical conditions

    • if(<condition>)
    • else if
    • else
  • Loops, repeat a chunk of code several times

    • repeat
    • for
    • while

If then else

if(<condition>) {
  
  <do something>
    
} else {
  
  <do something else>
  
}

If the <condition> evaluates to TRUE, then something gets executed, otherwise something else gets executed.

<condition> must be length one. No vectors allowed.

Examples

This is more useful when the condition inside the if is a result of some other computation

Examples

Examples

There does not need to be anything returned from the expression, it could just modify data, make a figure, etc.

if(log_transform) {
  
  data$Y <- log(data$Y)
  
}

Many if else

There is no limit to the amount of if else statements. This is equivalent to having if statements repeatedly nested.

Logical operators

& (logical AND) and | (OR) have scalar counterparts, called “short-circuit” operators

  • && and || evaluate the first argument, and then the second one only if necessary.

Common use case:

Other logical operators

  • xor Exclusive OR
  • isTRUE and isFALSE
  • any and all for converting logical vectors to a single value, also have na.rm option

Exception handling

aka, how to not stop evaluation on an error. R has 3 types of exceptions: 1) Errors, 2) Warnings, 3) Messages. Errors stop the flow of execution, all three say something at the console.

Warnings and Messages can be suppressed by wrapping the expressions in suppress(Warhings|Messages)

tryCatch evaluates an expression and does something with the error that you decide.

ifelse

This is a function, not a statement like if and else.

It is vectorized and hence better suited for working with data.

ifelse(<logical vector>, <yes vector>, <no vector>). All three vectors should be the same length or recycling happens.

It returns a vector with elements from yes when TRUE, and elements from no when FALSE.

Loops

Basic concepts

A loop repeatedly and sequentially evaluates an expression, i.e.,

{
  <stuff contained inside curly brackets>
}

A loop will continue forever unless you tell it to stop. You tell it to stop in different ways for different loop expressions

Repeat

This is the simplest of loops, it will repeat an expression until it encounters break

This will run forever

repeat {
  print("hello")
}

This will run exactly once

Modify the above to run 5 times

i <- 1
repeat {
  print("hello")
  if(i == 5) break
  i <- i + 1
}

While

Notice the pattern, repeat an expression until a condition is met.

The condition usually depends on a variable that changes at each iteration, in this case i, the iterator

while loops explicitly state the condition at the start:

For loops

A for loop explicitly states the sequence of the iterator at the start. Then the “end condition” is that the loop has reached the end of the sequence.

In this case, it is the most concise. I personally use for loops more than any other loop.

break can be used inside any loop to end it. next can be used to go to the next iteration.

Example - Iterating through species

Bootstrap

Nested loops

A loop can itself contain a loop, or multiple loops.

Note on speed

You may see people warn you not to use for loops in R, “because they are slow”.

That is partially true, but speed is not the only thing, for loops can be much clearer and more understandable than the alternatives.

But, the slow thing in R is changing the size of an object, so you can avoid that by creating a vector/matrix/array of the correct size to hold the results of the loop:

system.time({
A1 <- NULL
for(i in 1:100000) {
  A1 <- c(A1, rnorm(1))
}
})
   user  system elapsed 
 12.513   0.222  12.807 
system.time({
A2 <- numeric(100000)
for(i in 1:length(A2)) {
  A2[i] <- rnorm(1)
}
})
   user  system elapsed 
  0.073   0.000   0.073 

Practical

  1. Practice working if and else statements
  2. Practice working with loops

Link to lesson

Link home