Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Control Flow and Functions

Conditionals: if, else, ifelse and switch

Make decisions in R code with if, else if and else, the vectorized ifelse(), switch() and case_when(). Learn && versus &, any(), all() and common conditional mistakes.

Programs need to make decisions: print a warning only if a value is too large, choose a tax rate depending on the country, label each row "pass" or "fail". Conditionals let your code take different paths depending on whether something is TRUE or FALSE. R has two families: if/else for deciding once about a single value, and the vectorized ifelse() for deciding element by element over a whole vector.

if, else if and else

R
temperature <- 31

if (temperature > 30) {
  print("Hot")
} else if (temperature > 15) {
  print("Mild")
} else {
  print("Cold")
}
#> [1] "Hot"

The condition in parentheses must be a single TRUE or FALSE. R checks each branch from the top and runs only the first one that matches. The final else is optional and catches everything left over.

Two layout rules matter:

  • Use curly braces { } around each branch. They are optional for one-line bodies, but always using them avoids bugs.
  • When the code is typed at the top level (in the console or a script, not inside a function or other braces), else must be on the same line as the closing brace. This is why you write } else { rather than putting else on a new line.
R
# This fails at the top level: R finishes the if after the first }
if (temperature > 30) {
  print("Hot")
}
else {
  print("Not hot")
}
#> Error: unexpected 'else' in "else"

if is an expression and returns a value, so you can assign its result:

R
label <- if (temperature > 30) "hot" else "not hot"
label
#> [1] "hot"

Conditions must be length one

Because if expects one answer, giving it a vector is an error in modern R (version 4.2 and later):

R
if (c(TRUE, FALSE)) print("hi")
#> Error in if (c(TRUE, FALSE)) print("hi") : the condition has length > 1

Missing values cause an error too, since the condition is neither true nor false:

R
x <- NA
if (x > 5) print("big")
#> Error in if (x > 5) print("big") : missing value where TRUE/FALSE needed

Guard against that by checking is.na(x) first.

Combining conditions: && and ||

Inside if, use the double operators. They work on single values and stop early (short-circuit):

R
age <- 25
has_ticket <- TRUE

if (age >= 18 && has_ticket) {
  print("Welcome in")
}
#> [1] "Welcome in"
  • && is AND: both must be true. If the left side is FALSE, the right side is never evaluated.
  • || is OR: at least one must be true. If the left side is TRUE, the right side is skipped.
  • ! negates.

The single versions & and | are vectorized: they compare whole vectors element by element and are for filtering data, as in x[x > 1 & x < 5]. A handy consequence of short-circuiting is safe checks:

R
x <- NULL
if (!is.null(x) && x > 5) print("big") else print("nothing to check")
#> [1] "nothing to check"

Here x > 5 would have caused trouble with NULL, but it is never reached.

Testing many values: any(), all(), %in%

To turn a vector of logicals into one decision:

R
scores <- c(55, 72, 91)

any(scores > 90)
#> [1] TRUE

all(scores >= 60)
#> [1] FALSE

"b" %in% c("a", "b", "c")
#> [1] TRUE

any() is true if at least one is TRUE, all() if every one is. Add na.rm = TRUE when NA values are present. isTRUE(x) is true only when x is exactly one TRUE, which is a safe way to use a possibly messy value in an if.

ifelse(): decide for every element

ifelse(test, yes, no) goes through a vector and picks from yes or no for each position:

R
marks <- c(45, 82, 67, 90)
ifelse(marks >= 50, "pass", "fail")
#> [1] "fail" "pass" "pass" "pass"

You can nest calls for more than two outcomes, but it gets hard to read:

R
ifelse(marks >= 80, "high", ifelse(marks >= 50, "mid", "low"))
#> [1] "low"  "high" "mid"  "high"

For three or more categories the dplyr package offers case_when(), which reads like a list of rules:

R
library(dplyr)

case_when(
  marks >= 80 ~ "high",
  marks >= 50 ~ "mid",
  TRUE        ~ "low"
)
#> [1] "low"  "high" "mid"  "high"

Rules are checked in order, and the first match wins. TRUE ~ ... acts as the catch-all. You will use case_when() inside mutate() in dplyr Basics.

Which one when? if/else controls the flow of your program with a single condition. ifelse() and case_when() build new vectors, typically a new column.

switch(): choose by value

switch() selects one result by matching a name, and is tidy when you have many fixed choices:

R
unit <- "km"

switch(unit,
  km = "kilometers",
  mi = "miles",
  "unknown unit"        # unnamed last item is the default
)
#> [1] "kilometers"

If nothing matches and there is no default, switch() returns NULL invisibly. With a number instead of text, it picks by position: switch(2, "a", "b", "c") returns "b".

Flow of a decision

flowchart TD
    A["Start"] --> B{"temperature > 30?"}
    B -- "TRUE" --> C["Hot"]
    B -- "FALSE" --> D{"temperature > 15?"}
    D -- "TRUE" --> E["Mild"]
    D -- "FALSE" --> F["Cold"]

Figure: the if / else if / else chain from the first example.

Common mistakes

  1. if (x = 5): a single = assigns. Use ==.
  2. Passing a vector to if. Reduce it with any() or all(), or use ifelse().
  3. Putting else on its own line at the top level.
  4. Comparing text with the wrong case: "Yes" == "yes" is FALSE. Use tolower() first.
  5. Forgetting NA: a condition that evaluates to NA stops the program.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which operator should you use between two single conditions inside if?

    && works on single values and short-circuits; & is vectorized and meant for filtering vectors.
  2. 2. What does ifelse(c(1, 5, 10) > 4, "big", "small") return?

    ifelse tests each element separately.
  3. 3. Why does if (NA > 3) print("x") fail?

    The condition evaluates to NA, giving "missing value where TRUE/FALSE needed".
  4. 4. At the top level of a script, which layout is valid?

    R must see else on the same line as the closing brace, or it considers the if finished.
  5. 5. What does any(c(FALSE, TRUE, FALSE)) return?

    any() is TRUE when at least one element is TRUE.

Summary

  • if (cond) { } else if (cond) { } else { } runs the first matching branch; the condition must be a single TRUE or FALSE.
  • Use && and || inside if; use & and | for vectors.
  • any(), all() and %in% reduce or test vectors.
  • ifelse() and case_when() choose element by element; switch() chooses by value.
  • Watch for NA conditions and misplaced else.

Next: Loops