Skip to main content
R Programming
CHAPTER 06 Beginner

Conditional Statements and Loops

Updated: May 18, 2026
5 min read

# CHAPTER 6

Conditional Statements and Loops in R

1. Chapter Introduction

Control flow directs the logic path of your programs. This chapter covers R's complete flow control toolkit — conditional branching and looping constructs — with a focus on vectorized alternatives that make R code faster and more idiomatic.

2. Conditional Statements

r
12345678910111213141516171819202122232425262728293031323334
# ─── IF STATEMENT ────────────────────────────────────
score <- 75

if (score >= 60) {
  cat("PASS\n")
}

# ─── IF-ELSE ─────────────────────────────────────────
if (score >= 90) {
  cat("Grade: A\n")
} else if (score >= 80) {
  cat("Grade: B\n")
} else if (score >= 70) {
  cat("Grade: C\n")
} else if (score >= 60) {
  cat("Grade: D\n")
} else {
  cat("Grade: F\n")
}
# Output: Grade: C

# ─── INLINE IF (one-liner) ───────────────────────────
result <- if (score >= 60) "PASS" else "FAIL"
cat(result, "\n")  # PASS

# ─── IFELSE() — VECTORIZED (the R way) ───────────────
scores <- c(92, 45, 78, 61, 88, 55, 70)
grades <- ifelse(scores >= 90, "A",
           ifelse(scores >= 80, "B",
           ifelse(scores >= 70, "C",
           ifelse(scores >= 60, "D", "F"))))
print(grades)  # "A" "F" "C" "D" "B" "F" "C"

# Key insight: ifelse() works on entire vector at once — no loop needed!

3. For Loops

r
12345678910111213141516171819202122232425262728293031323334
# Basic for loop
for (i in 1:5) {
  cat("Iteration:", i, "\n")
}

# Loop over a vector
fruits <- c("apple", "banana", "cherry", "date")
for (fruit in fruits) {
  cat("Processing:", toupper(fruit), "\n")
}

# Loop with index
students <- c("Alice", "Bob", "Carol", "David")
scores   <- c(92, 78, 85, 61)

for (i in seq_along(students)) {
  cat(sprintf("%-10s → %.0f → %s\n",
              students[i], scores[i],
              ifelse(scores[i] >= 70, "PASS", "FAIL")))
}

# Loop over data frame rows
employees <- data.frame(
  name   = c("Alice", "Bob", "Carol"),
  dept   = c("IT", "HR", "Finance"),
  salary = c(85000, 55000, 70000)
)

for (i in 1:nrow(employees)) {
  bonus <- employees$salary[i] * 0.10
  cat(sprintf("%s (%s): Base=$%g, Bonus=$%g\n",
              employees$name[i], employees$dept[i],
              employees$salary[i], bonus))
}

4. While and Repeat Loops

r
12345678910111213141516171819202122232425262728293031323334353637383940
# ─── WHILE LOOP ──────────────────────────────────────
n <- 1
while (n <= 5) {
  cat("n =", n, "\n")
  n <- n + 1  # Always ensure termination condition!
}

# Practical: compound interest until target
balance <- 10000; rate <- 0.05; years <- 0; target <- 15000
while (balance < target) {
  balance <- balance * (1 + rate)
  years   <- years + 1
}
cat(sprintf("Reached $%.2f after %d years\n", balance, years))
# Reached $15078.68 after 9 years

# ─── BREAK and NEXT ──────────────────────────────────
# break: exit loop immediately
for (i in 1:10) {
  if (i == 5) break    # Stop when i reaches 5
  cat(i, "")
}  # 1 2 3 4

cat("\n")

# next: skip current iteration (like continue)
for (i in 1:10) {
  if (i %% 2 == 0) next  # Skip even numbers
  cat(i, "")
}  # 1 3 5 7 9

cat("\n")

# ─── REPEAT LOOP ─────────────────────────────────────
x <- 1
repeat {
  cat(x, "")
  x <- x + 1
  if (x > 5) break  # Must have break or it runs forever!
}  # 1 2 3 4 5

5. Mini Project: Grade Evaluation System

r
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
# ─── GRADE EVALUATION SYSTEM ─────────────────────────

evaluate_student <- function(name, math, science, english) {
  # Calculate average
  avg <- mean(c(math, science, english))

  # Assign grade
  grade <- if (avg >= 90)      "A (Excellent)"
            else if (avg >= 80) "B (Good)"
            else if (avg >= 70) "C (Average)"
            else if (avg >= 60) "D (Below Average)"
            else                "F (Fail)"

  # Subject performance
  subjects <- c(Math=math, Science=science, English=english)
  strongest <- names(which.max(subjects))
  weakest   <- names(which.min(subjects))

  list(name=name, avg=avg, grade=grade,
       strongest=strongest, weakest=weakest, scores=subjects)
}

# Class evaluation
class_data <- list(
  list("Alice",  92, 88, 76),
  list("Bob",    78, 82, 88),
  list("Carol",  85, 90, 84),
  list("David",  60, 55, 70),
  list("Eve",    95, 97, 89)
)

cat("=== GRADE EVALUATION REPORT ===\n\n")
results <- list()

for (student in class_data) {
  result <- evaluate_student(student[[1]], student[[2]], student[[3]], student[[4]])
  results[[student[[1]]]] <- result

  cat(sprintf("Student: %-8s | Avg: %5.1f | Grade: %s\n",
              result$name, result$avg, result$grade))
  cat(sprintf("  Strongest: %-10s | Needs work: %s\n",
              result$strongest, result$weakest))
}

# Class summary
all_avgs <- sapply(results, function(r) r$avg)
cat(sprintf("\n─── CLASS SUMMARY ───\n"))
cat(sprintf("Class Average: %.1f\n", mean(all_avgs)))
cat(sprintf("Highest:       %.1f (%s)\n", max(all_avgs), names(which.max(all_avgs))))
cat(sprintf("Lowest:        %.1f (%s)\n", min(all_avgs), names(which.min(all_avgs))))
cat(sprintf("Pass Rate:     %.0f%%\n", mean(all_avgs >= 60) * 100))

6. Common Mistakes

  • Modifying a vector while looping over it: Growing a vector inside a loop with result <- c(result, x) reallocates memory on every iteration — very slow for large loops. Pre-allocate: result <- vector("numeric", n).
  • Missing break in repeat: repeat { ... } without break creates an infinite loop that freezes R. Always have a break condition.

7. MCQs

Question 1

ifelse() advantage over if() in R?

Question 2

next in a loop?

Question 3

break in a for loop?

Question 4

seq_along(x) returns?

Question 5

Pre-allocating result vector before loop is faster because?

Question 6

while loop requires?

Question 7

repeat { ... } without break causes?

Question 8

R's preferred alternative to loops for vectorized operations?

Question 9

which.max(c(5,2,8,1)) returns?

Question 10

mean(all_avgs >= 60) * 100 calculates?

8. Interview Questions

  • Q: What is the difference between if() and ifelse() in R?
  • Q: Why should you avoid growing vectors inside for loops?

9. Summary

R control flow: if/else if/else for scalar branching, ifelse() for vectorized branching (preferred). for (i in sequence) for known iterations, while (condition) for conditional looping, repeat { break } for do-while pattern. break exits, next skips. Pre-allocate vectors before loops. R's vectorized idioms often eliminate the need for explicit loops entirely.

10. Next Chapter Recommendation

In Chapter 7: Functions in R, we master creating, documenting, and using functions — including anonymous functions, closures, and the apply family.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·