Control Flow
## Learning Objectives
- Master if, else if, else statements
- Understand switch statements
- Learn for, while, repeat loops
- Use break and next (continue)
- Apply family functions
## if Statement
### Basic if
```r
age <- 18
if (age >= 18) {
print("Adult")
}
```
### if-else
```r
age <- 15
if (age >= 18) {
print("Adult")
} else {
print("Minor")
}
```
### if-else if-else
```r
score <- 85
grade <- if(score >= 90) {
"A"
} else if (score >= 80) {
"B"
} else if (score >= 70) {
"C"
} else if (score >= 60) {
"D"
} else {
"F"
}
print(grade) # "B"
```
### Inline ifelse
```r
# Single line version
age <- 20
status <- if(age >= 18) "adult" else "minor"
```
## ifelse Function
### Vectorized Condition
```r
# ifelse for vectors
x <- 1:10
result <- ifelse(x > 5, "big", "small")
# "small" "small" "small" "small" "small" "big" "big" "big" "big" "big"
# Multiple conditions
score <- 75
grade <- ifelse(score >= 90, "A",
ifelse(score >= 80, "B",
ifelse(score >= 70, "C",
ifelse(score >= 60, "D", "F"))))
```
### with NA Handling
```r
x <- c(1, 2, NA, 4, 5)
ifelse(x > 2, "big", "small")
# "small" "small" NA "big" "big"
# With NA replacement
ifelse(is.na(x), 0, x)
# 1 2 0 4 5
```
## switch Statement
### Basic switch
```r
# By position
day <- 2
day_name <- switch(day,
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
)
print(day_name) # "Tuesday"
```
### By Name
```r
# By name (more readable)
color <- "red"
result <- switch(color,
"red" = "Stop",
"yellow" = "Slow down",
"green" = "Go"
)
print(result) # "Stop"
```
### With Default
```r
# No match returns NULL or last value
result <- switch("purple",
"red" = "Stop",
"green" = "Go"
)
print(result) # NULL
# Use default as last value
result <- switch("purple",
"red" = "Stop",
"green" = "Go",
"Unknown color"
)
print(result) # "Unknown color"
```
## for Loop
### Basic for
```r
# Loop through sequence
for (i in 1:5) {
print(i)
}
# 1, 2, 3, 4, 5
```
### Iterating Over Vectors
```r
# Loop through vector
fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
print(fruit)
}
# Using index
for (i in seq_along(fruits)) {
print(paste(i, fruits[i]))
}
```
### Nested for
```r
# Multiplication table
for (i in 1:3) {
for (j in 1:3) {
cat(i, "x", j, "=", i * j, "\n")
}
}
```
## while Loop
### Basic while
```r
i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}
# 1, 2, 3, 4, 5
```
### while with Condition
```r
# Read input until valid
value <- 0
while (value <= 0 || value > 100) {
value <- as.numeric(readline(prompt = "Enter 1-100: "))
}
```
## repeat Loop
### Infinite Loop with break
```r
# repeat is infinite loop (like while TRUE)
repeat {
print("This runs once")
break # Must have break condition
}
```
### repeat for Menu
```r
repeat {
cat("1. New Game\n")
cat("2. Load Game\n")
cat("3. Quit\n")
choice <- as.integer(readline(prompt = "Choose: "))
if (choice == 3) {
print("Goodbye!")
break
} else if (choice == 1) {
print("Starting new game...")
break
}
}
```
## break and next
### break - Exit Loop
```r
# Find first even number
numbers <- c(1, 3, 5, 6, 7, 8)
for (num in numbers) {
if (num %% 2 == 0) {
print(paste("First even:", num))
break
}
}
```
### next - Skip Iteration
```r
# Skip even numbers
for (i in 1:5) {
if (i %% 2 == 0) {
next # Skip to next iteration
}
print(i)
}
# 1, 3, 5
```
## Apply Family
### lapply - List Apply
```r
# lapply returns a list
nums <- list(a = 1:3, b = 4:6)
result <- lapply(nums, mean)
# $a: 2
# $b: 5
# Anonymous function
result <- lapply(nums, function(x) x * 2)
```
### sapply - Simplified Apply
```r
# sapply simplifies to vector if possible
nums <- list(a = 1:3, b = 4:6)
result <- sapply(nums, mean)
# a b
# 2 5
# Vector mode
result <- sapply(1:3, function(x) x^2)
# 1 4 9
```
### apply - Array/Matrix Apply
```r
mat <- matrix(1:9, nrow = 3)
# Apply function to rows (1) or columns (2)
apply(mat, 1, sum) # Row sums
apply(mat, 2, mean) # Column means
```
### vapply - Apply with Predefined Type
```r
# vapply is faster and safer
nums <- list(a = 1:3, b = 4:6)
result <- vapply(nums, mean, numeric(1))
# a b
# 2 5
```
### tapply - Table Apply
```r
# Apply function by groups
scores <- c(85, 90, 75, 95, 80)
groups <- c("A", "A", "B", "B", "A")
tapply(scores, groups, mean)
# A B
# 85 85
```
### mapply - Multiple Argument Apply
```r
# Apply function to multiple vectors
mapply(sum, 1:3, 10:12, 20:22)
# 31 34 37
# Same as
sum(1, 10, 20), sum(2, 11, 21), sum(3, 12, 22)
```
## Common Patterns
### Sum 1 to N
```r
# Vectorized (fast)
sum(1:100)
# Loop version
total <- 0
for (i in 1:100) {
total <- total + i
}
```
### Find in Vector
```r
numbers <- c(3, 7, 2, 9, 4)
target <- 9
for (num in numbers) {
if (num == target) {
print("Found!")
break
}
}
```
### Count Matches
```r
numbers <- c(1, 2, 3, 2, 4, 2, 5)
target <- 2
count <- 0
for (num in numbers) {
if (num == target) {
count <- count + 1
}
}
print(count) # 3
```
## Summary
- if/else if/else for conditional logic
- ifelse() for vectorized conditionals
- switch() for discrete value matching
- for loop for known iterations
- while loop for condition-based iteration
- repeat for infinite loops with break
- next skips iteration, break exits loop
- apply family: lapply, sapply, apply, vapply, tapply, mapply
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →