30-Day Course
Clinical SAS → R
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

TaskSAS®R
Assign new varbmi = wt/(ht/100)**2;mutate(bmi = wt/(ht/100)^2)
Two-way logicif x>0 then f='Y'; else f='N';if_else(x > 0, 'Y', 'N')
Multi-way logicif/else if chainscase_when(...)
RecodePROC FORMAT + put()case_when() / recode()

Code examples

case_when for age groups
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().