Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

if, else and ifelse()

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".

The shortcut

Before you write anything, count the answers you need. One answer for the whole situation: if. One answer per element: ifelse(). If you want if but have a vector, shrink it to one value first with sum(), any() or all().

Labelling every plot with ifelse(kg > 7, "heavy", "light")Step 1 of 4
  1. Test every element

    kg > 7 gives TRUE TRUE TRUE FALSE FALSE.

You can nest ifelse() for three bands: the inner call handles whatever the outer test sends to its no side.

Drills

Answer fast — trust the rule.

quick drill

What happens with if (kg > 7) print("heavy") in R 4.2 or later?

quick drill

With watered <- c(TRUE, FALSE, TRUE, TRUE, FALSE), what is ifelse(watered, "yes", "no")?

quick drill

What does x <- NA; if (x > 1) "big" else "small" do?

quick drill

What is size after size <- if (sum(kg) > 40) "big" else "small"?

quick drill

Which label does plot E (6 kg) get from ifelse(kg > 10, "high", ifelse(kg > 5, "mid", "low"))?

Remember

  • if asks one question; ifelse() asks every element.
  • Shortcut: count the answers you need. One means if; one per element means ifelse().
  • Trap: vector or NA conditions inside if, and else starting a new line.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainOne answer or five?

Explain why if (kg > 7) "heavy" else "light" fails for the garden's kg vector, and show two correct alternatives: one that labels every plot, and one that makes a single decision about the whole harvest.