Announcement Icon Online training class for Clinical R programming batch starts on Monday, 02Feb2026. Click here for details.

conditional logic - if_else - nested conditions


Lesson Description
-
  • Nested if_else() handles multiple conditions.
  • Readability drops as nesting increases.
  • For many conditions, prefer case_when().
library(dplyr)

# Sample data
dm <- tibble(
  USUBJID = c("101-001", "101-002", "101-003", "101-004"),
  age = c(35, 64, 19, 17)
)

dm02 <- dm %>%
  mutate(agegr1 = if_else(age >= 60, ">= 60 Years",
    if_else(between(age, 20, 59), "20 - < 60 Years", "< 20 Years")
  ))
  • Nested if_else() applies the next condition when the first is FALSE.
  • Use between() for range checks.
dm <- data.frame(
  USUBJID = c("101-001", "101-002", "101-003", "101-004"),
  age = c(35, 64, 19, 17),
  stringsAsFactors = FALSE
)

dm$agegr1 <- ifelse(dm$age >= 60, ">= 60 Years",
  ifelse(dm$age >= 20 & dm$age <= 59, "20 - < 60 Years", "< 20 Years")
)
  • Nested ifelse() mirrors the tidyverse logic.