Skip to the workspace
Pebellslearn by building
Basic Syntax  ›  Lesson

if, else and ifelse()

Conditional Statements 12 minif and else choose between blocks of code using a single TRUE or FALSE, while ifelse() makes the same kind of choice separately for every element of a vector.

r programming / if, else and ifelse()

Explore each scene at your own pace.

01 · The rule

The rule

if, else and ifelse()

if and else choose between blocks of code using a single TRUE or FALSE, while ifelse() makes the same kind of choice separately for every element of a vector.

Distinguish one control-flow decision from element-by-element selection.

Two questions arrive from the garden committee. "Was this a big week overall?" needs one answer. "Which plots were heavy?" needs an answer for every plot. R has a different tool for each, and mixing them up is one of the most common beginner errors.

The rule

if asks one question; ifelse() asks every element.

if and else run one block of code or another, based on a single TRUE or FALSE.

kg    <- c(12.5, 8, 15, 3.5, 6)
total <- sum(kg)   # 45

if (total > 40) {
  cat("Big week: share the surplus\n")
} else if (total > 20) {
  cat("Normal week\n")
} else {
  cat("Quiet week\n")
}

R checks the conditions from the top and runs the first block whose condition is TRUE, so this prints "Big week". Three rules:

  • The condition must be exactly one TRUE or FALSE. Since R 4.2, a longer condition such as if (kg > 7) is an error: the condition has length > 1.
  • An NA condition is also an error: missing value where TRUE/FALSE needed.
  • Keep } else { on one line. At the top level, R treats a line that ends with } as a finished statement, so an else on the next line is a syntax error.

if also returns a value, so it can sit on the right of an assignment:

size <- if (total > 40) "big" else "small"   # "big"

ifelse(test, yes, no) makes the choice for every element of a vector at once:

ifelse(kg > 7, "heavy", "light")
# "heavy" "heavy" "heavy" "light" "light"

For many fixed options keyed on a single value, switch() is tidier than a chain of else if: switch("bean", tomato = "red", bean = "green", "other") returns "green".

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.