Control structures determine the flow of execution in R programs. Master these to write efficient and dynamic R code.
R Control Structures
1. If-Else Statements
Make decisions in your code with conditional logic:
# Basic if statement
if (x > 10) {
print("x is greater than 10")
}
# If-else
if (score >= 60) {
print("Pass")
} else {
print("Fail")
}
# If-else if ladder
if (temp > 30) {
print("Hot")
} else if (temp > 20) {
print("Warm")
} else {
print("Cool")
}
If-Else Quiz
What's the correct syntax for an if statement?
2. For Loops
Iterate over sequences with for loops:
# Basic for loop
for (i in 1:5) {
print(i)
}
# Loop through vector
fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
print(fruit)
}
# Using seq_along (safer)
for (i in seq_along(fruits)) {
print(paste(i, fruits[i]))
}
For Loops Quiz
What does 1:5
generate in R?
3. While Loops
Execute code while a condition is TRUE:
# Basic while loop
count <- 1
while (count <= 5) {
print(count)
count <- count + 1
}
# Break statement
while (TRUE) {
num <- sample(1:10, 1)
print(num)
if (num == 7) break
}
While Loops Quiz
How do you exit a while loop early?
4. Vectorized Operations (Better Than Loops)
R works best with vectorized operations instead of loops:
# Instead of this loop:
result <- numeric(5)
for (i in 1:5) {
result[i] <- i * 2
}
# Do this:
result <- 1:5 * 2
# Apply functions
sapply(1:5, function(x) x^2) # Returns c(1,4,9,16,25)
# Logical indexing
nums <- 1:10
nums[nums > 5] # Returns 6,7,8,9,10
Vectorization Quiz
What's the R way to double all values in a vector?
×