6  Loops and conditionals

6.1 The for loop

There are occasions when we need to execute a specific set of code repetitively. These scenarios can be efficiently dealt with using loops. In programming a loop is a chuck of code that performs a certain task for a defined number of times or until a condition is met. Let’s say there is a collection of numbers and we want to calculate the square of each of these numbers. This scenario, as you can imagine, involves a repetitive task i.e. calculating the square. So, we can implement a loop which would iterate through this collection of numbers and calculate the square for each number. The for loop in R has two components – first is defining the number of iterations that need to be performed and second, is specifying the code that is to be executed at each iteration. The first part is enclosed within parentheses () and the second part within the

In the example below, after the for keyword, within parentheses, we have x in nums which define the number of iterations. Here, x is a new variable which would be assigned values from the nums vector one-by-one at each iteration. That is to say that x would have a value of 1 on the first iteration, 2 on second, 3 on third, and so on. Next, within curly braces, we have the code that we would like to execute on each iteration of the for loop. In our case, we want to print the square of the number (x). 

There are occasions when we need to perform execute a specific set to code repetitively. These scenarios can be efficiently dealt with using loops. In programming a loop is a chuck of code that performs certain task for defined number of times. E.g. lets say there is a collection of number and we want to calculate

nums <- c(1:5)
for(x in nums){
  print(x**2)
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

Similarly, we can iterate through a character vector as well. In this case, the variable within the for loop would be assigned the different value (from the vector) at each iteration.

fruits <- c("apple", "mango", "banana")
for(x in fruits){
  print(x)
}
[1] "apple"
[1] "mango"
[1] "banana"

6.1.1 Iterating with index

To get the index of the element along with the element of a vector, we have two options. First is to create a vector of numbers starting from one till the length of the vector to be iterated. Then iterate though this range vector.

for(x in c(1:length(fruits))){
  cat(x,fruits[x],"\n")
}
1 apple 
2 mango 
3 banana 

Another way to achieve this is by using the seq_along function. This function takes an argument along.with which should be an iteratable data type. It then creates a range starting from one to the length of the argument provided.

for(x in seq_along(fruits)){
  cat(x,fruits[x],"\n")
}
1 apple 
2 mango 
3 banana 

6.2 Conditional statement

Many times, when running a program, we need to check certain conditions and execute the particular code in case the condition is true and do something else otherwise. In these kinds of situations, we need to use conditional statements. The if statement specifies a condition and the corresponding code to execute when the condition is true. The else statement specifies the code to execute when the condition is not true. Note that in case of else there no condition is checked; it is executed when the condition given in if is false. The syntax involves specifying the condition after `if` keyword within parentheses and the corresponding code to be executed within curly braces. In case of else only the code is specified within curly braces. An important point to note here is that the else keyword must always appear after the closing of if curly braces. 

In the code below we have two variables x and y and a condition (within parentheses) which checks whether x > y. If this condition turns out to be true then it would print the corresponding statement within the curly braces and if x is less than y then the code block within the else curly braces would be executed. 

Warning: package 'DiagrammeR' was built under R version 4.3.2
x <- 5
y <- 6

if(x>y){
  print("x is greater than y")
} else{
  print("x is less than y")
}
[1] "x is less than y"

6.3 Nested if-else if

We can also check multiple conditions using something called as nested if block. In this case we’ll first check a condition with an if keyword, subsequently will have an else if keyword to check another condition along with its code block. Finally, there is the else keyword to execute the code block in case all the previously mentioned conditions are false. We can have as many else if as required.  

x <- 5
y <- 5

if(x>y){
  print("x is greater than y")
} else if (x<y){
  print("x is less than y")
} else{
  print("x is equal to y")
}
[1] "x is equal to y"

Quiz

Write a program to check the physical state of a substance given its boiling and freezing points. Ask the user to enter three values - temperature of the substance, boiling point, and freezing point. You may refer the flowchart below to understand the logic that needs to be followed.

Solution
temp1 <- as.double(readline("Please enter the temperature of the substance: "))
bp1 <- as.double(readline("Please enter the boiling point of the substance: "))
fp1 <- as.double(readline("Please enter the freezing point of the substance: "))
if(temp1 > bp1){
  print("The substance is gas.")
} else if(temp1 < fp1){
  print("The substance is solid")
} else {
  print("The substance is liquid")
}

6.4 while loop

Sometimes we need to execute a certain chunk of code repeatedly not for a specified number of iterations instead until a condition is met. In these kinds of situations we can use a while loop. A while loop has an implicit if condition wherein it checks the condition at each iteration and continues only if the condition is true. When the condition becomes false the loop is exited. The syntax for the while loop is very similar to the for loop such that we have the condition to to be checked within the parentheses and the code block within curly braces. 

 In the example below we have a variable x which is assigned a value of 5 and within the while loop there is a condition x > 2. Since the value of x is 5, so to begin with, the condition is true and therefore it would execute the code within the code block of the while loop. An important point to note here is that, in the code block, we have a statement that decreases the value of x by 1. This is important because the value of the variable (x) must change otherwise the loop will never end! After three iterations the value of x would not be greater than 2 (condition in the while statement) and then the loop will exit.

x <- 5
while (x > 2) {
  print(x)
  x <- x - 1
}
[1] 5
[1] 4
[1] 3

6.5 Controlling the execution of the loop

The loops, as discussed above, continue to execute a chunk of code for a specified number of iterations or until a condition is met. However, we have certain keywords to conditionally control the execution of the loop from within the loop. For example, we can at times skip the execution of the code at specific iterations depending on whether some condition is true or false. Also, we can prematurely terminate a loop if some sudden condition is true. This controlling of the loops can be achieved by using the next and the break keywords.

nums <- c(1:8)
for(x in nums){
  if(x==5){
    next
  }
  else{
   print(x) 
  }
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 6
[1] 7
[1] 8
nums <- c(1:8)
for(x in nums){
  if(x==5){
    break
  }
  else{
   print(x) 
  }
}
[1] 1
[1] 2
[1] 3
[1] 4

6.6 repeat loop

Similar to the while loop there is a repeat loop in R with a different that there is no checking of the condition at the beginning of the loop. This means that the repeat loop can be made to iterate at least once even if the condition to be checked is false at the beginning (not possible in case of the while loop). The repeat loop must have some conditional statement with the loop otherwise the loop would run infinitely.

x <- 2
repeat{   
  print(x)
  x <- x + 1
  if(x==5){
    break
    } 
  }
[1] 2
[1] 3
[1] 4