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

if / else

if and else let R choose what to do, like 'if it is cold wear a coat, else wear a t-shirt'. The code in a block only runs when its question is TRUE.

In this page:

  1. if / else
Syntax
r
if (condition) {
  # runs when TRUE
} else if (other_condition) {
  # runs when other_condition is TRUE
} else {
  # otherwise
}

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")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting else on a new line after the closing } at top level, as in } newline else {, which is a syntax error outside braces.
  2. Passing a vector of length greater than 1 as the condition, which is an error in recent R versions; use any() or all() or ifelse().
  3. Using = instead of == in the condition, which assigns rather than compares.
🔒

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.