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", "< 60 Years"))- For a two-branch condition in tidyverse, we use
if_else()from dplyr. if_else(age >= 60, ">= 60 Years", "< 60 Years")returns the first string where the condition is TRUE and the second where it is FALSE.- The function is strict: both sides of the branch must return the same type. That catches subtle bugs early — e.g. if one branch accidentally returns a number and the other a string.
- For NA input,
if_else()returns NA unless we supply an optional third argument specifying what to return for missing. - It is the tidyverse preferred alternative to base R
ifelse()precisely because of that type strictness.