Skip to Content
Course content

6: Control Flow Statements

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've got a vector of daily maximum temperatures from a sensor, but the data is a bit raw. Some days are scorching, some are freezing, and some are just... fine. I want to categorize these temperatures, but I'm not looking to use a fancy vectorized function right now; I want to build the logic myself so I can add more complex rules later. Let's see how R handles this.

The "Only the First One" Problem

My first instinct is to just use a simple if statement. I'll take my temperature vector and tell R to print a warning if any of the temperatures are below zero.

temps <- c(22, 15, -2, 30, 12)

if (temps < 0) {
  print("Watch out for frost!")
}

If you run this, R is going to throw a warning at you: "the condition has length > 1 and only the first element will be used". It might still print nothing because the first element (22) isn't less than zero, but that warning is R telling us that if is designed to handle a single TRUE or FALSE, not a whole vector of them. It's a common trip-wire. To check every single value, I need to iterate.

Walking Through the Data

Since I need to check each temperature one by one, a for loop is the right tool here. I'll set up an empty vector to hold my labels, then loop through the temperatures to fill it. I'll start with a simple binary: is it freezing or not?

temps <- c(22, 15, -2, 30, 12)
labels <- c()

for (t in temps) {
  if (t < 0) {
    labels <- c(labels, "Freezing")
  } else {
    labels <- c(labels, "Not Freezing")
  }
}

print(labels)
# Result: "Not Freezing" "Not Freezing" "Freezing" "Not Freezing" "Not Freezing"

That works, but "Not Freezing" is a bit vague. I'd rather have a "Hot" category for anything over 25 degrees. I can't just add another if inside the first one without making it nested and messy, so I'll use else if to create a chain of logic.

temps <- c(22, 15, -2, 30, 12)
labels <- c()

for (t in temps) {
  if (t < 0) {
    labels <- c(labels, "Freezing")
  } else if (t > 25) {
    labels <- c(labels, "Hot")
  } else {
    labels <- c(labels, "Moderate")
  }
}

print(labels)
# Result: "Moderate" "Moderate" "Freezing" "Hot" "Moderate"

Now the logic is more granular. The else if ensures that once a condition is met, R skips the rest of the chain for that specific iteration. It's much more efficient than running three separate if statements on every single number.

Stopping the Clock

Now, let's say I don't care about labeling the whole list. I just want to know the index of the first day the temperature dropped below zero—the first "frost event." A for loop would keep running through the whole vector even after I found my answer. That's a waste of cycles.

This is where a while loop comes in. I'll set a counter and tell R: "Keep going as long as the temperature is 0 or higher."

temps <- c(22, 15, -2, 30, 12)
i <- 1

while (temps[i] >= 0) {
  i <- i + 1
}

cat("The first frost occurred on day:", i)
# Result: The first frost occurred on day: 3

I have to be careful with while loops, though. If I had a vector where the temperature never dropped below zero, this code would keep incrementing i until it went past the end of the vector and crashed with an "out of bounds" error. In a real production script, I'd add a safety check like while (i <= length(temps) && temps[i] >= 0), but for this exploration, it shows exactly how to halt execution the moment a condition is met.




📋 Practical Task

The Sensor Outlier Flagging System

You are processing a stream of sensor readings. Some readings are valid, but some are "outliers" (too high or too low) and one specific value (NA) indicates a sensor failure that should stop the process immediately.

Write a script that does the following:

  • Create a vector called readings with these values: c(45, 110, 32, -10, 50, NA, 60).
  • Create an empty vector called status.
  • Use a while loop to iterate through the readings.
  • Inside the loop:
    • If the value is is.na(), stop the loop entirely (use break).
    • If the value is greater than 100, add "High" to status.
    • If the value is less than 0, add "Low" to status.
    • Otherwise, add "Normal" to status.
  • Print the final status vector to verify it stopped at the NA value and didn't process the final 60.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.