Day 7 of 30·Data Manipulation
Deriving Variables: mutate() vs. Assignment
Creating and transforming columns with mutate(), if_else() and case_when().
Learning objectives
- 1Create new columns with mutate().
- 2Translate IF/THEN/ELSE chains to case_when().
- 3Use if_else() for simple two-way logic.
- 4Derive several columns in one mutate() call.
Key SAS® → R comparison
| Task | SAS® | R |
|---|---|---|
| Assign new var | bmi = wt/(ht/100)**2; | mutate(bmi = wt/(ht/100)^2) |
| Two-way logic | if x>0 then f='Y'; else f='N'; | if_else(x > 0, 'Y', 'N') |
| Multi-way logic | if/else if chains | case_when(...) |
| Recode | PROC FORMAT + put() | case_when() / recode() |
Code examples
SAS®
if age<18 then agegr='<18';
else if age<65 then agegr='18-64';
else agegr='>=65';R
mutate(agegr = case_when(
age < 18 ~ "<18",
age < 65 ~ "18-64",
TRUE ~ ">=65"
))Note: case_when evaluates top to bottom; the TRUE branch is the catch-all ELSE.
Explanation
mutate() adds or overwrites columns while leaving the rest of the dataset untouched. It is the workhorse for derivations, and several assignments can live in one call, each able to reference columns created earlier in the same call.
case_when() replaces long IF/ELSE-IF ladders with an aligned, readable block — invaluable for grouping and flag derivations that reviewers must verify against a spec.
Practice exercise
Derive AGEGR1 (<18 / 18-64 / >=65), a BMI column, and an obesity flag (BMI>=30) in a single mutate().