R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
6: Control Flow Statements
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
readingswith these values:c(45, 110, 32, -10, 50, NA, 60). - Create an empty vector called
status. - Use a
whileloop to iterate through thereadings. - Inside the loop:
- If the value is
is.na(), stop the loop entirely (usebreak). - 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.
- If the value is
- Print the final
statusvector to verify it stopped at theNAvalue and didn't process the final60.
There are no comments for now.