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

conditional logic - if_else


Lesson Description
-
  • if_else() is a dplyr function for single-condition logic.
  • Use it when you have only one mutually exclusive condition.
  • For multiple 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", "< 60 Years"))
  • if_else() takes a condition, a TRUE value, and a FALSE value.
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", "< 60 Years")
  • ifelse() is the base R equivalent for vectorized conditions.