2.4 Loops and conditions

This section reviews two of the most basic elements of any programming language: if statements and cycles or loops.

2.4.1 if statements

The basic form of an if statement in R is as follows:

if(condition){true_action}

Condition must return a Boolean, either TRUE or FALSE. If TRUE then the code follows the code within the curly brackets and performs the true_action. If condition is FALSE the code does nothing.

It is more customary to also give a chunk of code for the case condition is FALSE. This can be achieved with else.

if(condition){true_action} else {false_action}

Let’s see an example.

a <- 5
if (a < 2){"hello"} else {"goodbye"}
## [1] "goodbye"

The variable a is assigned the number 5. Then we impose a condition: if a is less than 2, we print the text "hello", otherwise "goodbye" is printed. Since a <- 5 the code prints correctly "goodbye". On the other hand if a were assigned 1.

a <- 1
if (a < 2){"hello"} else {"goodbye"}
## [1] "hello"

2.4.2 ifelse

if works when checking a single element and the condition returns either TRUE or FALSE. The command ifelse can be used to quickly check a condition over all elements of a vector. Consider the following example.

vec <- c(1, 3, 5, 7, 9)
ifelse(vec > 5, "bigger", "smaller")
## [1] "smaller" "smaller" "smaller" "bigger"  "bigger"

vec contains the values 1, 3, 5, 7, 9 and the condition is if an elemenent of vec is larger than 5. If TRUE the code returns the string bigger and otherwise returns smaller. The code above returns therefore a vector of the same length of vec including either the string bigger or the string smaller.

2.4.3 Loops

for loops are used to iterate over items in a vector. They have the following skeleton:

for(item in vector) {perform_action}

For each item in vector, perform_action is performed once and the value of item is updated each time.

Here is an example.

for (i in c(1,2,3)){
  print(i)
}
## [1] 1
## [1] 2
## [1] 3

Item is the variable i (it is costumary to use just a letter) and at each step i is set equal to a value in the vector c(1,2,3). At each of these iterations, the command print(i), which simply returns the value that i takes is called. Indeed we see that the output is the sequence of numbers 1, 2, 3.