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
3. For Loops
r
4. While and Repeat Loops
r
5. Mini Project: Grade Evaluation System
r
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 { ... }withoutbreakcreates an infinite loop that freezes R. Always have abreakcondition.
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()andifelse()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.