← Back to R Course | Chapter 4: Control Flow | Lesson 1 of 6

if / else

In this page:

  1. if / else

if / else

An if statement runs a block only when its condition is TRUE; an optional else runs otherwise. The condition must evaluate to a single logical value, not a vector -- using a vector condition triggers an error or warning depending on the R version. else must appear on the same line as the closing brace of the if block when written across multiple lines.

Warning: The condition in if() must be a single TRUE/FALSE value, not a vector -- use ifelse() or all()/any() for vectorized conditions.

Example: if / else

markup
score <- 85

if (score >= 90) {
  cat("Grade: A\n")
} else if (score >= 70) {
  cat("Grade: B\n")
} else {
  cat("Grade: C\n")
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.