R (tidyverse)+
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")
))- For three-branch logic in tidyverse, we can nest
if_else()calls — the "else" value of the outer call is itself anotherif_else(). - The outer
if_else(age >= 60, ..., ...)handles the 60+ case. The innerif_else(between(age, 20, 59), ..., ...)handles the 20-59 and everything-else cases. between(age, 20, 59)is a dplyr helper equivalent toage >= 20 & age <= 59— a small readability boost for the simple case.- Each branch must return the same type, same as the non-nested
if_else(). - For more branches, prefer
case_when()— see the case_when lesson (1865). Nesting gets hard to read past three levels.