3. Everything is Under Control

You learn to take control of your R codes with control structures. You will learn your first step to automation with conditional statements and loops.
Author

Nien Xiang Tou

Published

October 9, 2024

Image generated by generative AI.

Learning Goals

  • Learn if-else statement syntax
  • Learn for loop syntax
  • Learn while loop syntax

Control Structures

Control structures in programming are tools that manage the flow of execution in your code based on specific conditions or repetitions. They allow your program to make decisions using if-else statements, or to perform tasks repeatedly with loops like for and while. By using control structures, you can make your code dynamic, efficient, and able to respond intelligently to different inputs or scenarios.

If-Else Statements

If-else statements are common conditional statements that allow codes to choose between two or more actions based on a specified condition.

In R, the syntax for an if-else statement follows this structure:

Here’s a simple example of an if-else statement to check whether a number is odd or even. Try changing the number and re-running the code.

Exercise 3.1

Write a code using if-else statements that check a person’s age and prints out their age category. The categories are:

  • “Non-adult” if the person is under 21 years old
  • “Adult” if the person is 21 and above
  • “Older-adult” if the person is 65 and above
if (age >= 65) {
  print("This person is an older adult")
} else if (age >= 21) {
  print("This person is an adult")
} else {
  print("This person is a non-adult")
}

For Loops

For loops in programming are control structures that allow you to execute a block of code repeatedly for a specified number of iterations. They are particularly useful for iterating over sequences, such as lists or vectors, enabling you to perform repetitive tasks efficiently. By defining a loop variable and a range, for loops help automate processes that require the same operation to be applied multiple times, streamlining code and enhancing productivity.

In R, the syntax for a for loop follows this structure:

Here’s an example of printing numbers from 1 to 10:

Exercise 3.2

In this exercise, we will use a for loop to simulate a six-sided dice roll. The possible outcomes of the dice are reflected in the object below named dice.

The sample() function is used to randomly select one of the possible outcomes. Complete the following code to simulate rolling the dice for ten trials.

for (i in 1:trials){
  outcome <- sample(dice, 1)
  print(outcome)
}

Exercise 3.3

Incorporate if-else statements to check whether each outcome is an odd or even number and print a message accordingly.

for (i in 1:trials){
  outcome <- sample(dice, 1)
  print(outcome)
  if (outcome %% 2 == 0){
    print("The outcome is an even number.")
  } else {
    print("The outcome is an odd number.")
  }
}

While Loops

While loops in programming are control structures that repeatedly execute a block of code as long as a specified condition remains TRUE. Unlike for loops, which iterate a set number of times over a sequence, while loops are more flexible and can run indefinitely until the condition is no longer met, making them suitable for situations where the number of iterations is not predetermined. This dynamic nature allows while loops to handle a broader range of scenarios but requires careful management of the condition to avoid infinite loops.

In R, the syntax for a while loop follows this structure:

Similar to the for loop example of printing 1 to 10 above, we can use the while loop to achieve the same output.

While loops run as long as a specified condition remains true, making them ideal when the number of iterations isn’t predetermined. This has different applications as compared to for loops. For example, we may employ a while loop and break condition to the dice rolling exercise to find out how many trials are needed to roll a 4.