SyntaxStudy
Sign Up
R Conditionals: if, else, ifelse, and switch
R Beginner 1 min read

Conditionals: if, else, ifelse, and switch

Conditional execution in R uses the familiar if / else if / else syntax. The condition must evaluate to a single TRUE or FALSE value; a vector of length > 1 will trigger a warning (and an error in newer R versions). When you need a vectorised conditional, use the ifelse() function, which evaluates a condition element-wise over a vector and returns one of two values at each position. The dplyr::case_when() function is a readable multi-condition vectorised alternative. The switch() function provides a compact alternative to long chains of if / else if when you are selecting among a fixed set of character or numeric values. For character switching, you supply named arguments where each name is a possible value of the input expression and the value is what to return. A final unnamed argument acts as the default case. switch() is particularly useful inside function bodies when dispatching on a type or method argument. Conditional expressions in R are themselves expressions that return a value, which means you can use them on the right-hand side of an assignment. This makes it natural to write code like result <- if (condition) value_a else value_b without needing a temporary variable. Combined with R's functional style, this makes for expressive, side-effect-free code.
Example
# Basic if / else if / else
x <- 17

if (x < 0) {
    cat("negative\n")
} else if (x == 0) {
    cat("zero\n")
} else {
    cat("positive\n")
}

# if as an expression (returns a value)
label <- if (x %% 2 == 0) "even" else "odd"
cat(x, "is", label, "\n")

# Nested if
classify <- function(n) {
    if (n < 0) {
        "negative"
    } else if (n < 10) {
        "small positive"
    } else if (n < 100) {
        "medium positive"
    } else {
        "large positive"
    }
}
classify(-3)   # "negative"
classify(7)    # "small positive"
classify(250)  # "large positive"

# ifelse() — vectorised conditional
scores <- c(45, 72, 58, 90, 33, 81)
ifelse(scores >= 60, "pass", "fail")
# "fail" "pass" "fail" "pass" "fail" "pass"

# Chained ifelse (poor readability; prefer dplyr::case_when)
grade <- ifelse(scores >= 90, "A",
         ifelse(scores >= 80, "B",
         ifelse(scores >= 70, "C",
         ifelse(scores >= 60, "D", "F"))))
grade   # "F" "C" "F" "A" "F" "B"

# switch() — dispatch on a value
describe_type <- function(type) {
    switch(type,
        numeric   = "a number",
        character = "a string",
        logical   = "TRUE or FALSE",
        "unknown type"         # default
    )
}
describe_type("numeric")    # "a number"
describe_type("logical")    # "TRUE or FALSE"
describe_type("list")       # "unknown type"