R control flow uses if, else, for, while, and repeat—similar to Python but with parentheses around conditions and braces for blocks.
if / else
score <- 85
if (score >= 90) {
grade <- "A"
} else if (score >= 80) {
grade <- "B"
} else {
grade <- "C"
}
for loops (prefer vectorization when possible)
total <- 0
for (x in c(1, 2, 3, 4)) {
total <- total + x
}
Vectorized sum() is idiomatic—loops remain useful for side effects and complex logic.
Important interview questions and answers
- Q: Truthy values in R?
A: Only TRUE/FALSE are logical; non-zero numbers and non-empty strings are not auto-boolean—use explicit comparisons. - Q: Vectorized if?
A: Useifelse()for element-wise conditions on vectors.
Self-check
- How do you write else if in R?
- When prefer vectorization over for loops?
Tip: Prefer vectorized ops and ifelse() over loops for numeric transforms.
Interview prep
- ifelse use case?
Vectorized conditional assignment across entire vectors.