Learn R · 4/15

Control Flow: Making Decisions in Code

9 min read

Course: R

Topic 4: Control Flow: Making Decisions in Code

Hey there! Welcome to one of the most fundamental parts of programming in R (or any language, really). So far, you've learned how to store data and call functions. But what happens when you want your code to do different things based on the data it sees? Or what if you need to do the same task a thousand times?

That's where Control Flow comes in. It's how we give our code a "brain" to make decisions and repeat actions.

Imagine you're programming a mail-sorting robot for a futuristic post office. 🤖 Right now, the robot can pick up a package, but it doesn't know what to do with it. Control flow gives us the tools to tell the robot: "If the package is fragile, put it in the 'Handle with Care' bin. For each package in this giant mailbag, scan its barcode. While there are still letters on the conveyor belt, keep processing them."

This guide will walk you through giving your R code these decision-making superpowers.


1. Conditional Logic: if, else, and the vectorized ifelse 🤔

The Problem: Our mail-sorting robot is holding a package. It needs to decide where it goes. Is it a priority shipment? Is it international? Is it just standard mail? The robot can't put it in all three bins; it has to choose one based on some information, like a stamp or a label.

The Solution: We use conditional statements to execute code only when a certain condition is met.

if Statement

The if statement is your most basic decision-making tool. It works just like it sounds: if a condition is true, then do something.

The structure is simple:
if (condition) {
// code to execute if condition is TRUE
}

The condition part has to be something that results in either TRUE or FALSE.

r
# Let's check a package's weight
package_weight_kg <- 22

# If the package is heavier than 20kg, it needs a special "Heavy" sticker.
if (package_weight_kg > 20) {
  print("This package is heavy! Add a 'Heavy' sticker.")
}

Run this, and you'll see the message. If you change package_weight_kg to 15, nothing will happen, because the condition is FALSE.

if...else Statement

This is great, but what if we want to do something else when the condition is FALSE?

The Problem: Our robot checks for a "Priority" stamp. If it's there, it goes in the priority bin. But if it's not there, what should it do? Right now, it does nothing. We need to tell it what to do in the other case.

The Solution: We add an else block.

if (condition) {
// code to execute if condition is TRUE
} else {
// code to execute if condition is FALSE
}

r
# Let's check for a specific shipping class
shipping_class <- "Standard"

if (shipping_class == "Priority") {
  print("Sorting into the PRIORITY bin.")
} else {
  print("Sorting into the STANDARD bin.")
}
# Output: [1] "Sorting into the STANDARD bin."

You can even chain these together with else if to handle multiple conditions.

r
# Our robot can now handle three types of mail
shipping_class <- "International"

if (shipping_class == "Priority") {
  print("Sorting into the PRIORITY bin.")
} else if (shipping_class == "International") {
  print("Sorting into the INTERNATIONAL bin.")
} else {
  print("Sorting into the STANDARD bin.")
}
# Output: [1] "Sorting into the INTERNATIONAL bin."

The Mighty ifelse() Function ✨

The Problem: A whole conveyor belt of packages arrives! We have a list (a vector) of their weights. Do we have to check them one by one with a clunky if statement? That sounds slow and inefficient.

The Solution: R is built for vectors, and ifelse() is the perfect tool for this job. It performs a check on every single item in a vector and returns a new vector with the results.

Its structure is: ifelse(test_condition, value_if_true, value_if_false)

r
# A vector of package weights
package_weights <- c(5, 25, 10, 30, 15)

# We want to create a new vector of labels: "Standard" or "Heavy"
# The rule: if weight > 20, it's "Heavy". Otherwise, it's "Standard".

labels <- ifelse(package_weights > 20, "Heavy", "Standard")

print(labels)
# Output: [1] "Standard" "Heavy" "Standard" "Heavy" "Standard"

Look at that! One clean line of code did the work of a much longer if/else structure. In the data science world, you'll work with huge datasets. "Vectorized" functions like ifelse() are industry standard because they are incredibly fast and efficient.


2. For Loops: Iterating Over Sequences and Collections 🔁

The Problem: The robot has a mailbag with 50 packages. We need it to perform the exact same action—scan the barcode—on each one. Writing scan(package1), scan(package2), etc., 50 times would be a nightmare and impossible if the number of packages changes.

The Solution: A for loop. It's designed to perform an action for each item in a collection (like a vector or a list).

The structure is:
for (variable_name in sequence) {
// code to execute for each item
}

The variable_name is a temporary placeholder you create. In each loop iteration, it will hold the current item from the sequence.

r
# A vector of package tracking numbers
tracking_numbers <- c("ZA123", "QB789", "CC456", "FX001")

# Let's loop through them and "scan" each one
for (tracking_num in tracking_numbers) {
  # In the first loop, tracking_num will be "ZA123"
  # In the second, it will be "QB789", and so on.
  print(paste("Scanning package:", tracking_num))
}

# Output:
# [1] "Scanning package: ZA123"
# [1] "Scanning package: QB789"
# [1] "Scanning package: CC456"
# [1] "Scanning package: FX001"

This is a cornerstone of automation. You can use for loops to iterate through rows in a data frame, files in a folder, or items in a list. It's your go-to tool for repetitive tasks on a known number of items.


3. While Loops: Iterating Based on Conditions ⏳

The Problem: The packages are no longer in a finite mailbag. They are on a long conveyor belt that keeps moving. We don't know if there are 10 packages or 10,000. We need the robot to keep working as long as there are packages on the belt.

The Solution: A while loop. A for loop runs for a specific number of items. A while loop runs as long as a condition is TRUE.

The structure is:
while (condition) {
// code to execute
// IMPORTANT: something inside the loop must eventually
// make the condition FALSE
}

🚨 A Word of Warning! The biggest danger with while loops is creating an infinite loop. This happens if the condition never becomes false. Imagine telling our robot, "Keep working while the power is on." It will never stop and will eventually overheat, crash, and cry digital tears. Always make sure your loop has a way to end!

r
# Let's simulate a conveyor belt with 5 packages
packages_on_belt <- 5

while (packages_on_belt > 0) {
  print(paste("Packages remaining:", packages_on_belt))
  print("Processing one package...")
  
  # This is the crucial part! We change the value
  # that the condition is checking.
  packages_on_belt <- packages_on_belt - 1
  
  print("-----------------------")
}

print("All packages processed. The belt is empty!")

# Output:
# [1] "Packages remaining: 5"
# [1] "Processing one package..."
# [1] "-----------------------"
# [1] "Packages remaining: 4"
# ... and so on until ...
# [1] "Packages remaining: 1"
# [1] "Processing one package..."
# [1] "-----------------------"
# [1] "All packages processed. The belt is empty!"

while loops are perfect for situations where you don't know the number of iterations beforehand, like reading a file until you reach the end or running a simulation until a goal is met.


4. Loop Control: Using break and next 🚦

The Problem: Our robot is dutifully processing packages from a mailbag (for loop).

  1. Suddenly, it scans a package that is leaking a mysterious green goo. It shouldn't just continue scanning the rest of the packages; it needs to stop immediately and call the Hazmat team.
  2. In another scenario, it picks up a letter with a smudged, unreadable address. It can't process this letter, but it doesn't need to stop its entire job. It should just put it aside and move on to the next letter.

The Solution: We need finer control inside our loops.

break: The Emergency Stop 🛑

The break statement immediately terminates the entire loop it's inside. The code will then continue running after the loop block.

r
# A list of packages to process. One of them is... problematic.
package_contents <- c("Books", "Clothes", "Leaking Green Goo", "Toys", "Electronics")

for (item in package_contents) {
  print(paste("Processing package with:", item))
  
  if (item == "Leaking Green Goo") {
    print("EMERGENCY! Halting all operations!")
    break # Exit the loop NOW!
  }
}

print("Loop finished. The area is now safe... hopefully.")

# Output:
# [1] "Processing package with: Books"
# [1] "Processing package with: Clothes"
# [1] "Processing package with: Leaking Green Goo"
# [1] "EMERGENCY! Halting all operations!"
# [1] "Loop finished. The area is now safe... hopefully."

Notice how "Toys" and "Electronics" were never processed. break provides an essential escape hatch.

next: Skip to the Next Iteration ⏭️

The next statement skips the rest of the current iteration and jumps straight to the beginning of the next one.

r
# A vector of package weights. Some are invalid (negative).
package_weights <- c(10, 5, -2, 8, -5, 12)

for (weight in package_weights) {
  if (weight < 0) {
    print(paste("Invalid weight detected:", weight, "- Skipping."))
    next # Skip this iteration and go to the next weight
  }
  
  print(paste("Processing package with weight:", weight))
}

# Output:
# [1] "Processing package with weight: 10"
# [1] "Processing package with weight: 5"
# [1] "Invalid weight detected: -2 - Skipping."
# [1] "Processing package with weight: 8"
# [1] "Invalid weight detected: -5 - Skipping."
# [1] "Processing package with weight: 12"

Using break and next makes your loops smarter and more robust, allowing them to handle exceptions and special cases gracefully.


Further Reading 📚

To dive deeper into the official documentation and see more examples, check out these resources.

Challenge

Challenge: Sensor Data Processing Pipeline

You are given a vector of raw sensor readings, sensor_readings. Your task is to write an R script that processes this data according to a specific set of rules to create a status log. You must use a combination of vectorized functions and loops to achieve this.

Requirements:

  1. First, create a new vector called processed_readings. Use the ifelse() function to sanitize the sensor_readings data: any negative value should be replaced with NA, while all non-negative values should remain unchanged.
  2. Initialize an empty character vector named status_log to store the results of your analysis.
  3. Implement a for loop that iterates through each element of the processed_readings vector.
  4. Inside the loop, apply the following logic:
    • If an element is NA, use the next statement to immediately skip to the next iteration.
    • For valid numerical readings, use an if...else if...else structure to classify the reading and append the corresponding string to the status_log vector:
      • 0 to 50 (inclusive): Append "Stable"
      • 51 to 85 (inclusive): Append "Warning"
      • 86 to 100 (inclusive): Append "Alert"
      • Greater than 100: Append "CRITICAL"
    • If a reading is classified as "CRITICAL", after appending it to the log, you must immediately terminate the loop using the break statement.

Expected result

After executing your code, there should be a character vector named status_log in the environment.

Given the initial sensor_readings, the status_log vector should contain the following values in this exact order:

css
["Stable", "Stable", "Warning", "Alert", "Warning", "Alert", "CRITICAL"]

Explanation of the output:

  • The two negative values (-15, -5) are skipped due to the next statement.
  • The loop processes all values up to 105.
  • When the value 105 is processed, it is classified as "CRITICAL", appended to the log, and the break statement immediately stops the loop. Therefore, the subsequent values (34, 78, 91) in the sensor_readings vector are not processed.
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.